[php] Keep values selected after form submission

Consider:

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

This question is related to php javascript html wordpress forms

The answer is


I don't work in WordPress much, but for forms outside of WordPress, this works well.

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>

After trying all these "solutions", nothing work. I did some research on W3Schools before and remember there was explanation of keeping values about radio.

But it also works for the Select option. See below for an example. Just try it out and play with it.

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

If you are using WordPress (as is the case with the OP), you can use the selected function.

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

Just change this line:

 <input type="submit" value="Submit" class="submit" />

with this line:

 <input type="submit" value="Submit/Reload" class="submit" onclick="history.go(-1);">

JavaScript 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]);

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

Try this solution for keep selected value in dropdown:

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

This works for me!

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

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

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

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to wordpress

#1273 – Unknown collation: ‘utf8mb4_unicode_520_ci’ How to get WooCommerce order details Wordpress plugin install: Could not create directory WooCommerce: Finding the products in database How to get post slug from post in WordPress? How to get featured image of a product in woocommerce Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\wordpress\wp-includes\class-http.php on line 1610 Use .htaccess to redirect HTTP to HTTPs Load More Posts Ajax Button in WordPress How to decode encrypted wordpress admin password?

Examples related to forms

How do I hide the PHP explode delimiter from submitted form results? React - clearing an input value after form submit How to prevent page from reloading after form submit - JQuery Input type number "only numeric value" validation Redirecting to a page after submitting form in HTML Clearing input in vuejs form Cleanest way to reset forms Reactjs - Form input validation No value accessor for form control TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"