Home > Backend Development > PHP Tutorial > How Can I Preserve Dropdown Selection Values in an HTML Form After Submission?

How Can I Preserve Dropdown Selection Values in an HTML Form After Submission?

Linda Hamilton
Release: 2024-12-09 00:08:10
Original
543 people have browsed it

How Can I Preserve Dropdown Selection Values in an HTML Form After Submission?

Preserving Form Values After Submission

When working with HTML forms, it's often desirable to keep the selected values in dropdown elements after the form is submitted. This ensures a seamless user experience, as previously chosen options remain selected.

Implementation

In PHP, using WordPress, this can be achieved using JavaScript to retrieve the selected values from the form's query string parameters.

Consider the following HTML form:

<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>
Copy after login

JavaScript Solution

To automatically update the selected values without using if-else structures, JavaScript can be employed:

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

This script retrieves the selected values from the URL's query string and sets them as the selected values in the dropdown elements.

By using this method, the selected options will remain preserved even after the form is submitted and the page is reloaded.

The above is the detailed content of How Can I Preserve Dropdown Selection Values in an HTML Form After Submission?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template