How to capture the text of an Select option?
So I have this:
<select id="list">
<option value="1">This is Me</option>
<option value="2">This is You</option>
<option value="3">And this is Mr. Nukem</option>
</select>
How would I go about grabbing the 'text' of the options here? The problem is, it needs to be 'dynamic', in the sense I need the text for the currently selected option...
I know a manual, static way of getting the text...
document.getElementById('list').options[1].text
That will grab "This is You"... But how do I get it for the currently selected option? Since I can't simply use:
开发者_如何学Cdocument.getElementById('list').value
As that will grab the number... :-(
var list = document.getElementById('list');
var text = list.options[list.selectedIndex].text;
See (for example) here https://developer.mozilla.org/en/DOM/HTMLSelectElement
If you can use jQuery, you can try something like this:
$("#list").change(function() {
alert($(this).find("option[value=" + $(this).val() + "]").text());
});
See http://jsfiddle.net/MWu9f/ for a working example.
$("#list option[value='2']").text()
You can use this jQuery line and it will solve your problem.
In this an element with id list which has a property value equal to 2. What you want is the option child of the list.
The jQuery solution is like this:
$("#list option:selected").text()
精彩评论