Get text of the selected option with jQuery [dupli

2019-01-25 01:52发布

问题:

This question already has an answer here:

  • Get selected text from a drop-down list (select box) using jQuery 31 answers

I have a select box with some values. How do I get the selected options text, not the value?

<select name="options[2]" id="select_2">
    <option value="">-- Please Select --</option>
    <option value="6" price="0">100</option>
    <option value="7" price="0">125</option>
    <option value="8" price="0">150</option>
    <option value="9" price="0">175</option>
    <option value="10" price="0">200</option>
    <option value="3" price="0">25</option>
    <option value="4" price="0">50</option>
    <option value="5" price="0">75</option>
</select>

I tried this:

$j(document).ready(function(){
    $j("select#select_2").change(function(){
        val = $j("select#select_2:selected").text();
        alert(val);
    });
});

But it's coming back with undefined.

回答1:

Close, you can use

$('#select_2 option:selected').html()


回答2:

$(document).ready(function() {
    $('select#select_2').change(function() {
        var selectedText = $(this).find('option:selected').text();
        alert(selectedText);
    });
});

Fiddle



回答3:

Change your selector to

val = j$("#select_2 option:selected").text();

You're selecting the <select> instead of the <option>



回答4:

You could actually put the value = to the text and then do

$j(document).ready(function(){
    $j("select#select_2").change(function(){
        val = $j("#select_2 option:selected").html();
        alert(val);
    });
});

Or what I did on a similar case was

<select name="options[2]" id="select_2" onChange="JavascriptMethod()">
  with you're options here
</select>

With this second option you should have a undefined. Give me feedback if it worked :)

Patrick



回答5:

Also u can consider this

$('#select_2').find('option:selected').text();

which might be a little faster solution though I am not sure.