Reputation: 10575
How do we write Equivalent value of this in Jquery
document.getElementById( "selectbox").
options[document.getElementById("selectbox").selectedIndex].innerText;
Upvotes: 1
Views: 676
Reputation: 48240
The OPs Javascript example is unnecessarily repetitive and complex. It shows plain Javascript in a bad light compared to jQuery when in fact it should be simpler and more concise. This is really not something jQuery should be used for.
document.getElementById('selectbox').value;
Was that so hard? With the element reference stored in a variable it would be as simple as this
selectbox.value;
And For comparison, the jQuery code
$('#selectbox').val();
IMO the plain Javascript is more readable, direct, and certainly more performant.
I would hardly consider this question academic as the example code is so trivial; it does not involve DOM traversal and has no cross browser compatibility issues, which are the main things jQuery was designed to address. So what the point is I'm not really sure...
Upvotes: 0
Reputation: 239291
You want to selected the selected <option>
within the <select id="selectbox">
tag and get its text:
$('#selectbox option:selected').text()
Because the selectbox can't really contain anything but options, you can omit that part:
$('#selectbox :selected').text()
Upvotes: 5
Reputation: 382696
Like this:
$('#selectbox option:selected').text();
To get it on change
event, you can do like this:
$('#selectbox').change(function(){
alert($('option:selected', $(this)).text());
});
Upvotes: 4