0

How to remain selected value of dropdown after click on submit button?? THANK YOU!!!

I have a dropdown list like this: <form method="post" action=""> <select name="pet" id="pet_id"> <option selected>all</option> <option value="1">cat</option> <option value="2">dog</option> <option value="3">bird</option> </select> <button name="btn" type="submit">Search</button> </form> How to remain selected value of dropdown after click on submit button?? Please help me, I need it ASAP! Thank you!!!!!

9th Apr 2021, 6:49 PM
PR PRGR
PR PRGR - avatar
8 Answers
+ 2
use e.preventDefault() ; like this form.addEventListener("submit", function(e) { e.preventDefault(); }) that code will prevent the default refresh of the browser
9th Apr 2021, 6:57 PM
Med Amine Fh
Med Amine Fh - avatar
+ 2
PR PRGR Did I say to learn Ajax? I didn't say you to learn Ajax. I just gave you solution. If you don't know how to use Ajax / JSON properly then see this example. Here he used JSON. Either you use Ajax or JSON in both cases you don't need to refresh whole page and no need worry about resetting selection after submitting data. https://code.sololearn.com/Wh0929Edy46J/?ref=app See this link also to know how to work with Ajax/PHP/SQL https://www.google.com/amp/s/www.bitdegree.org/learn/php-ajax-example/amp
10th Apr 2021, 3:13 AM
A͢J
A͢J - avatar
+ 1
I'm not sure I understand your question, but in case you wanted to reset the drop down menu back to the "selected" option, you can use document.getElementById("pet_id").selectedIndex = 0 // choose whichever index you need
9th Apr 2021, 7:11 PM
Russ
Russ - avatar
+ 1
PR PRGR If you are working with PHP then don't use form. Use Ajax to submit data on server side without refreshing page. So you don't need to maintain your selected value. Your selected value will be remain selected until you don't reset through JavaScript or jQuery.
9th Apr 2021, 7:23 PM
A͢J
A͢J - avatar
0
Russ Med Amine Fh I mean that if user choose option "cat" and press button "submit" the page will refresh and show pictures with cats from database. And I want to see that user's selected option ( in select area), but it shows me option by default.
9th Apr 2021, 10:28 PM
PR PRGR
PR PRGR - avatar
0
Med Amine Fh if I'll prevent page refreshing - will I see needed results from database? I thought it need to refresh, no?
9th Apr 2021, 10:31 PM
PR PRGR
PR PRGR - avatar
0
🅰🅹 (Challenge Accepted) Interesting, didn't know about this.. How many time do I need to learn AJAX?
9th Apr 2021, 10:34 PM
PR PRGR
PR PRGR - avatar
10th Apr 2021, 11:19 AM
PR PRGR
PR PRGR - avatar