问题
I know that this might be very simple question and I tried to find solutions in the web but I can't figure it... I have the following C# / ASPX code:
SelectArea += "<select name=\"Area\" id=\"area\">" + "<option value=\"Default\" style=\"display:none;\">SELECT AREA</option>";
for (i = 0; i < ds.Tables[0].Rows.Count; i++)
{
AreaName = ds.Tables[0].Rows[i]["AreaName"].ToString();
SelectArea += string.Format("<option value=\"{0}\"/>{0}</option>", AreaName);
}
SelectArea += "</select>";
And this javascript function that happeen after submit
function validateProfile() {
var el = document.getElementById("area").value;
alert(el);
}
I want some how to get the number of the selected value in the list. I tried with the code above but it doesn't work.
wish for help, thanks!
回答1:
For example if you have
<select id="myselect">
<option value="1">value1</option>
<option value="2" selected="selected">value2</option>
<option value="3">value3</option>
</select>
To get selected option do:
var selects = document.getElementById("myselect");
var selectedValue = selects.options[selects.selectedIndex].value;// will gives u 2
var selectedText = selects.options[selects.selectedIndex].text;// gives u value2
Sample JsFiddle
回答2:
Try with this
var el = document.getElementById("area");
var selectedArea = el.options[el.selectedIndex].value;
回答3:
Try :
var myList = document.getElementById("area");
var selectedValue = myList.options[myList.selectedIndex].value;
var selectedText = myList.options[myList.selectedIndex].text;
来源:https://stackoverflow.com/questions/16719412/get-value-from-select-list-in-js