views:

109

answers:

5

How do we write Equivalent value of this in Jquery

     document.getElementById( "selectbox").
     options[document.getElementById("selectbox").selectedIndex].innerText;
+4  A: 

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());
});
Sarfraz
+5  A: 

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()
meagar
+9  A: 
$('#selectbox option:selected').text();
BoltClock
The child selector is superfluous - select elements can't be nested. :)
Tomalak
@Tomalak: fine, I've eaten it now.
BoltClock
+1  A: 

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...

MooGoo
A: 

I tried but there is no change in the value. I am getting error with the thing. Is this the right one. Once again I'll check whether I was wrong or not...


design agency website