简体   繁体   中英

Set selected on options using PHP / JS

I have a list of ~80 option values, I know there must be an easy way to do this with javascript, would anyone be willing to spare me a moment of their time?

First and foremost, $sid is a get variable pulled from the url (whatever.php?sid=CR01)

Sadly, all option values are hard coded -__- inherited this project

<select name="siteid"  size="15">
    <option value="CR01" <?php if ($sid == 'CR01') { echo 'selected="selected"';} ?>>
         CR01 (Crooked Run @ Lake Frederick Dam)
    </option>
<option value="'CR02'">CR02 (Nineveh Spring)</option>
<option value="'CR03'">CR03 (Crooked Run @ Rt 639 bridge)</option>
<option value="'CR04'">CR04 (McKay Spring)</option>
<option value="'CR05'">CR05 (Crooked Run @ Cabin Ct)</option>
(etc etc etc)
</select>

oh yes ofcourse there is an easy way.

IN PHP

$opts = array(
    'CR01' => '...',
    'CR02' => '...',
    ....
);

<select name="siteid">
<?php foreach( $opts as $var => $opt ): ?>
  <option 
    value="<?php echo $var ?>"
    <?php if( $var == $sid ): ?>selected="selected"<?php endif; ?> >
   <?php echo $opt ?>
  </option>
<?php endforeach; ?>
</select>

IN JS

VANILLA

function setOption(selectElement, value) {
  var options = selectElement.options;
  for (var i = 0, optionsLength = options.length; i < optionsLength; i++) {
    if (options[i].value == value) {
        selectElement.selectedIndex = i;
        return true;
    }
  }
  return false;
}
setOption(
  document.querySelector('select[name='siteid']'),
  "<?php echo $sid; ?>"
);

as described here

JQUERY

$("select[name='siteid'] option[value='<?php echo $sid; ?>']").prop('selected', true)

With Javascript? Why Js? I would use a PHP, to avoid repeating code. Assuming that you have all your options stored in an array, I would do:

<select name="siteid"  size="15">
    <?php foreach ( $options as $option ) : ?>
    <option value="'.$option['value'].'"<?php echo ($option['selected'] == 1) ? ' selected="selected"':''?>> <?php echo $option['label'] ?> </option>
    <?php endoreach; ?>
</select>

You should get the values from the database, with a sql wich marked a field named selected as 0 if it's not the id, or 1 if it is. This way, you save a crazy amount of coding

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM