Home > Net >  Set option as selected with php
Set option as selected with php

Time:03-23

How can I use PHP to set the select option to the one that was chosen when the form was sent? This is my code where I am stuck:

<?php
  if(isset($_POST['btSubmit'])) {
    $selectedOption = $_POST['s']; // Value of selected option … but how to use it below?
  }
?>
<form action="<?php echo $_SERVER['SCRIPT_NAME']; ?>" method="POST">
  <select name="s">
    <option value="" selected disabled>-- choose one --</option>
    <option value="a">choose a</option>
    <option value="b">choose b</option>
  </select>
  <input type="submit" name="btSubmit">
</form>

So when you send the form with a selected on the next load of the page the a should be selected by default.

CodePudding user response:

Just add the selected="selected" attribute to the option tag that you received under $_POST['s'].

<?php
  $selectedOption = '';
  if(isset($_POST['btSubmit'])) {
    $selectedOption = $_POST['s']; // Value of selected option … but how to use it below?
  }

  function injectSelectedAttribute($selectedOption, $option_value){
    return strtolower($selectedOption) === strtolower($option_value) ? 'selected="selected"' : '';
  }
?>
<form action="<?php echo $_SERVER['SCRIPT_NAME']; ?>" method="POST">
  <select name="s">
    <option value=""  disabled>-- choose one --</option>
    <option value="a" <?php echo injectSelectedAttribute($selectedOption, 'a'); ?>>choose a</option>
    <option value="b" <?php echo injectSelectedAttribute($selectedOption, 'b'); ?>>choose b</option>
  </select>
  <input type="submit" name="btSubmit">
</form>

You can further improve this to echo HTML of the options via looping on a PHP array of select options.

CodePudding user response:

Try this,
    <?php
      if(isset($_POST['btSubmit'])) {
        $selectedOption = $_POST['s']; // Value of selected option … but how to use it below?
      }
    ?>
    <form action="<?php echo $_SERVER['SCRIPT_NAME']; ?>" method="POST">
      <select name="s">
        <option value="" selected disabled>-- choose one --</option>
        <option value="a" <?php echo $selectedOption==a?'selected':'' ;?>>choose a</option>
        <option value="b" <?php echo $selectedOption==b?'selected':'' ;?>>choose b</option>
      </select>
      <input type="submit" name="btSubmit">
    </form>
  • Related