Home >Backend Development >PHP Tutorial >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>
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>
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!