Specify a default item for HTML form drop-down forms

Usually, when you need to select the default item, follow these steps:

<select>
  <option value="1">                 Volvo  </option>
  <option value="2" selected="true"> Saab  </option>
  <option value="3">                 Mercedes  </option>
  <option value="4">                 Audi  </option>
</select>

Is it possible to get something like this?

<select selectedValue="2">
  <option value="1">  Volvo  </option>
  <option value="2">  Saab  </option>
  <option value="3">  Mercedes  </option>
  <option value="4">  Audi  </option>
</select>

This is easier in PHP, since you only need to program a single value, instead of processing the selected attribute in any way possible <option/>.

+3
source share
5 answers

Place JavaScript after the list is declared and set the highlighted index there:

<script>
document.getElementById('listBoxId').selectedIndex=<?php echo $INDEX ?>;
</script>

Something like that.

+3
source

<select> , . , <option> , , :

$selected = "2";
foreach($values as $key => $val) {
    echo "<option value=\"" . $key . "\"" . ($key == $selected ? " selected=\"selected\">" : ">") . $val . "</option>";
}

( PHP , 100% )

+7

, id,

<select id="default-value-2">

<option value="2" <?php echo is_this_the_default_value ? selected='true' : '' ?>

- (, php, , ).

, , selected = "selected", . ,

+3

:

$value = 1;

<select>
<?php if($value==1) echo "<option selected='true'> Volvo </option>";
else echo "<option> Volvo </option>"; ?>
<?php if($value==2) echo "<option selected='true'> Saab </option>";
else echo "<option> Saab </option>"; ?>
</select>
+1

I found that I was looking for this to see if there is a better way to do this.

The best and clean answer is from @roryf, however, if you don't loop your data, I thought it would be much cleaner to wrap it with a function:

function set_selected($desired_value, $new_value)
{
    if($desired_value==$new_value)
    {
        echo ' selected="selected"';
    }
}

Then you will use it as follows:

<?php $selected_value = 2; ?>

<select>
    <option value="1"<?php set_selected('1', $selected_value); ?>> Volvo  </option>
    <option value="2"<?php set_selected('2', $selected_value); ?>> Saab  </option>
    <option value="3"<?php set_selected('3', $selected_value); ?>> Mercedes  </option>
    <option value="4"<?php set_selected('4', $selected_value); ?>> Audi  </option>
</select>

This would set Saab as the chosen one :)

0
source

Source: https://habr.com/ru/post/1762439/


All Articles