Keep values selected after form submission

2019-01-02 18:12发布

<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>

On submitting the form, how do I make sure that the selected values remain selected in the dropdowns? This form is inside wordpress (PHP).

10条回答
怪性笑人.
2楼-- · 2019-01-02 18:53

Since wordpress already uses jquery you can try something like this:

var POST=<?php echo json_encode($_POST); ?>;
for(k in POST){
  $("#"+k).val(POST[k]);
}
查看更多
大哥的爱人
3楼-- · 2019-01-02 18:56

Js only solution:

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];
    }
}

or if you are using jquery you can replace

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

with:

 $('*[name="'+tmparr[0]+'"]').val(tmparr[1]);
查看更多
闭嘴吧你
4楼-- · 2019-01-02 19:00
<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>
查看更多
大哥的爱人
5楼-- · 2019-01-02 19:07

To avoid many if-else structures, let javascript do the trick automatically:

 <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>
查看更多
登录 后发表回答