Search code examples
phphtmlselectoptgroup

option selected value and optgroup PHP


i have a similar code as this which is pretty works fine but i am looking a way to make the codes shorter, but i don't have any idea how to do this because it checks the selected value from the DB then have the option selected + the option has its own optgroup

<select name="server">
  <?php if ($server == 'A') { ?>
  <optgroup label="Label 1">
    <option value="A" selected="selected">A</option>
    <option value="B">B</option>
  </optgroup>
  <optgroup label="Label 2">
    <option value="C">C</option>
    <option value="D">D</option>
  </optgroup>
  <?php } else if ($server == 'B') { ?>
  <optgroup label="Label 1">
    <option value="A">A</option>
    <option value="B" selected="selected">B</option>
  </optgroup>
  <optgroup label="Label 2">
    <option value="C">C</option>

and so on...

did you guys have any idea how to do this in php? any help is appreciated, thank you


Solution

  • You can use a ternary to achieve this

    <select name="server">
      <optgroup label="Label 1">
        <option value="A" <?php $server == 'A' ? echo 'selected="selected"' : ''; ?>>A</option>
        <option value="B" <?php $server == 'B' ? echo 'selected="selected"' : ''; ?>>B</option>
      </optgroup>
      <optgroup label="Label 2">
        <option value="C">C</option>
        <option value="D">D</option>
      </optgroup>
    

    Another option would be to use javscript. Just put the server inside a data-tag and fetch that in a script:

    <select name="server" data-server="<?= $server; ?>">
          <optgroup label="Label 1">
            <option value="A">A</option>
            <option value="B">B</option>
          </optgroup>
          <optgroup label="Label 2">
            <option value="C">C</option>
            <option value="D">D</option>
          </optgroup>
    </select>
    
    <script>
    
        var select = document.querySelector('select[name="server"]');
        var server = select.getAttribute('data-server');
        select.querySelector('option[value="' + server + '"]').setAttribute('selected', 'selected');
    
    </script>