Mantener los valores seleccionados después del envío del formulario


<form method="get" action="">
   <select name="name">
      <option value="a">a</option>
      <option value="b">b</option>
   </select>
   <select name="location">
      <option value="x">x</option>
      <option value="y">y</option>
   </select>
   <input type="submit" value="Submit" class="submit" />
</form>

Al enviar el formulario, ¿cómo me aseguro de que los valores seleccionados permanezcan seleccionados en los desplegables? Este formulario está dentro de wordpress (PHP).

Author: madth3, 2010-02-11

10 answers

Para evitar muchas estructuras if-else, deje que javascript haga el truco automáticamente:

 <select name="name" id="name">
  <option value="a">a</option>
  <option value="b">b</option>
 </select>

<script type="text/javascript">
  document.getElementById('name').value = "<?php echo $_GET['name'];?>";
</script>

 <select name="location" id="location">
  <option value="x">x</option>
  <option value="y">y</option>
 </select>

<script type="text/javascript">
  document.getElementById('location').value = "<?php echo $_GET['location'];?>";
</script>
 35
Author: Sarfraz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-02-13 06:19:06
<select name="name">
   <option <?php if ($_GET['name'] == 'a') { ?>selected="true" <?php }; ?>value="a">a</option>
   <option <?php if ($_GET['name'] == 'b') { ?>selected="true" <?php }; ?>value="b">b</option>
</select>
 19
Author: Ignacio Vazquez-Abrams,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-02-11 17:23:57

Después de probar al esto "resuelve" nada de trabajo. Hice alguna investigación sobre w3school antes y recuerde que había una explicación de mantener los valores sobre la radio. Pero también funciona para la opción Select. Vea aquí un ejemplo. Solo pruébalo y juega con él.

<?php
$example = $_POST["example"];
?>
<form method="post">        
<select name="example">
    <option <?php if (isset($example) && $example=="a") echo "selected";?>>a</option>
    <option <?php if (isset($example) && $example=="b") echo "selected";?>>b</option>
    <option <?php if (isset($example) && $example=="c") echo "selected";?>>c</option>
</select>
<input type="submit" name="submit" value="submit" />
</form>
 5
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-28 12:14:04

Dado que wordpress ya usa jquery, puedes probar algo como esto:

var POST=<?php echo json_encode($_POST); ?>;
for(k in POST){
  $("#"+k).val(POST[k]);
}
 3
Author: oda,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-23 03:58:55

Si está utilizando Wordpress (como es el caso con el OP), puede utilizar el selected función.

<form method="get" action="">
  <select name="name">
   <option value="a" <?php selected( isset($_POST['name']) ? $_POST['name'] : '', 'a' ); ?>>a</option>
   <option value="b" <?php selected( isset($_POST['name']) ? $_POST['name'] : '', 'b' ); ?>>b</option>
 </select>
 <select name="location">
   <option value="x" <?php selected( isset($_POST['location']) ? $_POST['location'] : '', 'x' ); ?>>x</option>
   <option value="y" <?php selected( isset($_POST['location']) ? $_POST['location'] : '', 'y' ); ?>>y</option>
 </select>
 <input type="submit" value="Submit" class="submit" />
</form>
 3
Author: Kalpesh Prajapati,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-06 17:48:18

Js solución única:

var tmpParams = decodeURIComponent(window.location.search.substr(1)).split("&");
for (var i = 0; i < tmpParams.length; i++) {
    var tmparr = tmpParams[i].split("=");
    var tmp = document.getElementsByName(tmparr[0])[0];
    if (!!tmp){
        document.getElementsByName(tmparr[0])[0].value = tmparr[1];
    }
}

O si está utilizando jquery puede reemplazar

 var tmp = document.getElementsByName(tmparr[0])[0];
 if (!!tmp){
     document.getElementsByName(tmparr[0])[0].value = tmparr[1];
 }

Con:

 $('*[name="'+tmparr[0]+'"]').val(tmparr[1]);
 2
Author: Lukas Ignatavičius,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-04-13 15:55:33

Esto funciona para mí!

<label for="reason">Reason:</label>
<select name="reason" size="1" id="name" >
    <option value="NG" selected="SELECTED"><?php if (!(strcmp("NG", $_POST["reason"]))) {echo "selected=\"selected\"";} ?>Selection a reason below</option>
    <option value="General"<?php if (!(strcmp("General", $_POST["reason"]))) {echo "selected=\"selected\"";} ?>>General Question</option>
    <option value="Account"<?php if (!(strcmp("Account", $_POST["reason"]))) {echo "selected=\"selected\"";} ?>>Account Question</option>
    <option value="Other"<?php if (!(strcmp("Other", $_POST["reason"]))) {echo "selected=\"selected\"";} ?>>Other</option>

</select>
 0
Author: TonyTee,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-26 01:32:30

Pruebe esta solución para mantener el valor seleccionado en el menú desplegable:

<form action="<?php echo get_page_link(); ?>" method="post">
    <select name="<?php echo $field_key['key']; ?>" onchange="javascript: 
       submit()">
    <option value="">All Category</option>
    <?php 
    foreach( $field['choices'] as $key => $value ){ 
       if($post_key==$key){ ?>
          <option value="<?php echo $key; ?>" selected><?php echo $value; ?></option>
<?php
   }else{?>
  <option value="<?php echo $key; ?>"><?php echo $value; ?></option>
 <?php }
  }?>
 </select>
</form>
 0
Author: Heena Patel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-07 05:16:41

No trabajo mucho en WP, pero para formularios fuera de Wordpress, esto funciona bien.

PHP

location = "";                                   // declare variable

if($_POST) {
    if(!$_POST["location"]) {
        $error .= "Location is required.<br />"; // If not selected, add string to error message
     }else{
        $location = $_POST["location"];          // If selected, assign to variable
     }

HTML

<select name="location">
    <option value="0">Choose...</option>
    <option value="1" <?php if (isset($location) && $location == "1") echo "selected" ?>>location 1</option>
    <option value="2" <?php if (isset($location) && $location == "2") echo "selected" ?>>location 2</option>
</select>
 0
Author: Douglas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-03 07:46:39
<form method="get" action="">
 <select name="name" value="<?php echo $_GET['name'];?>">
   <option value="a">a</option>
   <option value="b">b</option>
 </select>
 <select name="location" value="<?php echo $_GET['location'];?>">
   <option value="x">x</option>
   <option value="y">y</option>
 </select>
   <input type="submit" value="Submit" class="submit" />
</form>
 -1
Author: Adrian Preda,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-21 09:33:13