javascript jQuery 通过文本从选择框获取值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17502399/
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-10-27 08:33:48  来源:igfitidea点击:

jQuery get the value from selectbox by its text

javascriptjqueryhtmlcssselect

提问by nixon1333

I have a select box like this:

我有一个这样的选择框:

        <select id="year">
        <option value="1">1 Year</option>
        <option value="2">2 Years</option>
        <option value="3">3 Years</option>
        <option value="4">4 Years</option>
        <option value="5">5 Years</option>
        <option value="6">6 Years</option>
        <option value="7">7 Years</option>
        <option value="8">8 Years</option>
        <option value="9">9 Years</option>
        <option value="10">10 Years</option>
        </select>

I want to get value of a specific text in jQuery, like "value of 4 Years". How can I do that?

我想在 jQuery 中获取特定文本的值,例如“4 年的值”。我怎样才能做到这一点?

回答by undefined

Using filtermethod (exact match):

使用filter方法(完全匹配):

$('select option').filter(function(){
    return $(this).text() === '4 Years';
}).val();

Using :containsselector:

使用:contains选择器:

$('select option:contains(4 Years)').val();

回答by Falguni Panchal

Try using .text() on the selected option. e.g.:

尝试在所选选项上使用 .text() 。例如:

$('select option:selected').text();

回答by ezakto

If you want the value of the selected option:

如果您想要所选选项的值:

$('#year').val();

If you want a specific option by its text:

如果您希望通过文本获得特定选项:

$("#year option:contains('4 Years')").val();

Regards.

问候。