Skip to content Skip to sidebar Skip to footer

Stay On Selected Item On Drop Down Menu Using Javascript

What is happening is I'm trying to get the drop-down menu to STAY on what was selected but it keeps switching to the default after I hit submit. Can someone help me with the javasc

Solution 1:

Your title

Get selected text from a drop-down list (select box) using Javascript

is not the same question as your first sentence:

What is happening is I'm trying to get the drop-down menu to STAY on what was selected but it keeps switching to the default after I hit submit.

To get the text from the selected option in a drop-down list, you use

var e = document.getElementById('locale');
var text = e.options[e.selectedIndex].text;
console.log(text);

To get a form to keep its values after clicking a button of the type submit, it should work this way by default. From what I know, browsers don't have a reason to want to clear a drop-down field when clicking a button of the type submit.

You can always test stopping the browser's default behavior by including return false; in the onsubmit event.

<input value="Select"type="submit" onsubmit="GetSelectedItem(); return false;" />

Edit: And from your comment replies, it seems your actual question is something else entirely. If you want to retain the value of a drop-down list AFTER having left the page, you will need to store the value somewhere (most commonly a cookie, SessionStorage or a server-side session which is outside of the scope of Javascript).

I recommend this MDN article if you want to use SessionStorage.

Solution 2:

functionGetSelectedItem()
 {
     var index = document.getElementById("locale").selectedIndex;    
     alert("value =" + document.getElementById("locale").value); // show selected valuealert("text =" + document.getElementById("locale").options[index].text); // show selected text 
 }

Post a Comment for "Stay On Selected Item On Drop Down Menu Using Javascript"