I got a tutorial request from my website reader, he asked to “Keep values selected after form submission in PHP”. In this tutorial, I will share the simple code to keep form values selected in textbox after form submission.
Let’s start to create an example for this. Copy the below code and change it as per your requirement.
1 2 3 4 5 6 7 8 9 10 |
$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> |
Here is another way to keep selected values after form submitted using JavaScript code. This code will avoid the many if else statement in your code. simply set the form fields value in ID and use that ID in your form fields.
1 2 3 4 5 6 7 8 |
<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> |
Hope this tutorial help you. Do you like & share this article with your friends, and don’t forget to follow us on Facebook and Twitter to learn cool PHP tutorials.
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.
Article Tags: best php tutorials, form submission in php, get form data in javascript, get form data using php, php tutorial for beginners, php tutorials for beginners