Reputation: 323
I have this JavaScript for a dropdown menu, but I don't know how to take the selected value from it.
<select name="slist" >
<script language="javascript">
var states = new Array("Afghanistan", "Albania", "Algeria", "Andorra", "Angola", "Antarctica");
for (var hi = 0; hi < states.length; hi++)
document.write("<option value=\"" + states[hi] + "\">" + states[hi] + "</option>");
document.getSelection(states);
</script>
</select>
I've tried using this command:
document.getElementById("Label1").InnerHTML = states;
but it did not work. How to create a function that would give me the selected value in a label.text?
p.s. the dropdown menu is taken from www.hscripts.com
I forgot to mention that I have this menu in an update panel because I need a flicker free post back. when I click on my submit button the menu loses it's content, why?
Upvotes: 0
Views: 176
Reputation: 3541
What about this:
<select name="slist" id="slist">
<script language="javascript">
var states = new Array("Afghanistan", "Albania", "Algeria", "Andorra", "Angola", "Antarctica");
for (var hi = 0; hi < states.length; hi++)
document.write("<option value=\"" + states[hi] + "\">" + states[hi] + "</option>");
document.getSelection(states);
var sel = document.getElementById("slist");
sel.addEventListener('change', function() {
document.getElementById("Label1").innerHTML = sel.value;
});
</script>
</select>
<div id="Label1"></div>
Upvotes: 1
Reputation: 17366
You can try like this:
<select id="slist" name="slist" onchange="getSelectedState()">
....................
</select>
Your javascript function:
function getSelectedState(){
var elem = document.getElementById("slist"); //Get Element here
var state = elem.options[elem.selectedIndex].text; //Get value from dropdown or you can get text also
document.getElementById("selectedState").innerText = state; // initialize label here
}
Upvotes: 0
Reputation: 20418
Try this
For getting selected value after appending select box
var e = document.getElementById("slist");
var strUser = e.options[e.selectedIndex].value; //Getting Value
document.getElementById("Label1").InnerHTML = strUser //Appending value to your label
Upvotes: 0