Any way to define selected inside <select> tag rather than on

后端 未结 5 1704
-上瘾入骨i
-上瘾入骨i 2021-01-21 13:16

I have a weird html option list which I dont want to check each value to make it selected or not see the list below


                        
    
提交评论

  • 2021-01-21 13:51

    You can't change the <select> element to specify this: it's not part of the HTML specification. What you can do is give each option element an id and then use Javascript to set the right option element(s) as selected. In PHP, you would need to output the script snippet in the right place to get the browser to run it.

    For example

    <option value="7ft - 213cm" label="7ft - 213cm" id="s23">7ft - 213cm</option>
    ...
    <script>
    document.getElementById("s23").selected=true
    </script>
    
    0 讨论(0)
  • 2021-01-21 13:53

    If you don't want to use javascript, you're going to have to write the code you're avoiding.

    <? $selected = "6ft 10in - 208cm"; ?>
    <select name="height" id="height">
      <option value="" label="Select">Select Height</option>
      <? foreach ( $options as $option ): ?>
        <option value="<?= $option; ?>" <?= ($option == $selected ? "selected" : ""); ?> ><?= $option; ?></option>
      <? endforeach; ?>
    </select>
    
    0 讨论(0)
  • 2021-01-21 14:05

    You could always just write a helper function that gives you the <option> by passing it parameters. Something along the lines of

    function get_option($value, $selected_value) {
        return '<option value="' . $value . '" label="' . $value . '"' . ($value == $selected_value ? ' selected="selected"' : '') . '>' . $value . "</option>\n";
    }
    

    This will keep you from having to write it for each value, but instead just do

    $selected_value = '4ft 5in - 134cm';
    echo get_option('4ft 5in - 134cm', $selected_value);
    echo get_option('4ft 6in - 137cm', $selected_value);
    //etc, etc
    
    0 讨论(0)
  • 2021-01-21 14:12

    You can put all items in an array and dynamically generate the list with a for (or foreach) loop. Then just check in this loop whether your loopvariable equals your value and if so, assign the selected attribute.

    Something like this:

    <select name="height" id="height">
        <option value="" label="Select">Select Height</option>
        <?php
        $options = array("4ft 5in - 134cm", "4ft 6in - 137cm", "4ft 7in - 139cm", /* and all your other options ... */);
        $yourvalue = "4ft 6in - 137cm"; // or any valid entry
        foreach($options as $option) {
            echo '<option value="'.$option.'" label="'.$option.'" '. ($option == $yourvalue ? 'selected' : '') .'>'.$option.'</option>';
        }
        ?>
    </select>
    
    0 讨论(0)
  • 提交回复
    热议问题