Javascript 使用 jQuery 获取所选选项的文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6454016/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:48:31  来源:igfitidea点击:

Get text of the selected option with jQuery

javascriptjqueryhtmldrop-down-menujquery-selectors

提问by dotty

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.

但它回来了undefined

回答by JohnP

Close, you can use

关闭,您可以使用

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

回答by bancer

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

Fiddle

小提琴

回答by Bj?rn

Change your selector to

将您的选择器更改为

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

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

您正在选择<select>而不是<option>

回答by user1278890

Also u can consider this

你也可以考虑这个

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

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

尽管我不确定,这可能是一个更快的解决方案。

回答by PRacicot

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

帕特里克