Searching for a way to automatically get the name or id of a select box and use it to select the appropriate option from the url. Code given
I have the following drop down list and selects the opti开发者_如何学运维on based on the url e.g. www.domain.com/?car=Algema&city=Paris
The problem is thatI have 104 different forms and some of them are containg more than one dropdownlist. It is impossible to replace them. Is there a way to replace the $_GET['car']
with the $_GET['get the name of select id or name automatically']
?
Maybe a re-writing regex script that will replace all my php files?
<select name="car" id="car" class="select">
<option value="Algema" <?php echo $_REQUEST['car'] == 'Algema' ? 'selected="selected"' : '';?>>Algema</option>
<option value="Barkas" <?php echo $_REQUEST['car'] == 'Barkas' ? 'selected="selected"' : '';?>>Barkas</option>
<option value="Cadillac" <?php echo $_REQUEST['car'] == 'Cadillac' ? 'selected="selected"' : '';?>>Cadillac</option>
</select>
Use something less repetitive like this:
function makeSelect($name, $options) {
foreach ($options as &$option) {
$selected = isset($_GET[$name]) && $_GET[$name] == $option;
$option = sprintf('<option value="%1$s"%2$s>%1$s</option>',
htmlspecialchars($option),
$selected ? ' selected="selected"' : null);
}
return sprintf('<select name="%1$s" id="%1$s" class="select">%2$s</select>',
htmlspecialchars($name),
join($options));
}
$options = array('Algema', 'Barkas', 'Cadillac', …);
echo makeSelect('car', $options);
You can probably automate the extraction of the option names into the array format using a Regex, but you'll still have to confirm everything by hand at least.
精彩评论