简体   繁体   English

如何通过javascript中的选项获取选择框元素的值?

[英]How to get the value of a select box element by its option in javascript?

My select box is as follows: 我的选择框如下:

<select id='list'>
    <option value='1'>A</option>
    <option value='2'>B</option>
    <option value='3'>C</option>
</select>

I want to get the value of option - B without selecting it. 我想获取选项-B的值而不选择它。

With jQuery I can do the opposite ie get the text when I know the value through following: 使用jQuery,我可以做相反的事情,即当我通过以下方法知道值时获取文本:

$("#list option[value='2']").text();

But I want the reverse. 但我要相反。 I tried with following but not working: 我尝试了以下但不起作用:

 $("#owner option['B']").val();  

How can I do this? 我怎样才能做到这一点?

Use the :contains selector. 使用:contains选择器。

Assuming "owner" really is the ID of your <select> (it's "list" in your example), you can use: 假设“所有者”确实是您的<select>的ID(在您的示例中为“列表”),则可以使用:

 $("#owner option:contains('B')").val() // 2

您可以使用:contains(text)选择器,仅获取包含某些文本的元素:

$("#list option:contains('B')").val();

You can use .filter to get the right option element: 您可以使用.filter获取正确的option元素:

$("#list option").filter(function() {
    return $(this).text() == "B";
}).val();

http://jsfiddle.net/JWjKf/ http://jsfiddle.net/JWjKf/

try this 尝试这个

var b = $("#list").find('option:contains("B")').val();

see here : http://jsfiddle.net/MxpTZ/1/ 看到这里: http : //jsfiddle.net/MxpTZ/1/

Try this script 试试这个脚本

  $('#list option:contains("B")').prop('value') //jquery 1.6 or later

oR 要么

$('#list option:contains("B")').attr('value');

如果要按位置获取元素,可以执行以下操作:

$('#list').children().eq(1).val();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用Javascript通过选项的值在选择框中选择一个选项? - How to select an option in a select box by the value of the option using Javascript? 如何通过选项值获取选择元素 - How to get the select element by option value 如何在选择框选项值中获取输入文本字段的值 - How to get value of input text field in select box option value 如何使用 Javascript 获取选项元素的值(选自 select 列表)'value' 属性 - How to get the value of option element (selected from select list ) 'value' attribute using Javascript 如何在JavaScript中获取带空格的选择框值? - How to get select box value with space in javascript? 如何禁用 <option>在一个<select>基于它在 JavaScript 中的值?我有一个带有多个 &lt;option&gt; 的 &lt;select&gt; 。每一个都有独特的价值。我需要禁用具有给定定义值(而不是 innerHTML )的 &lt;option&gt; 。有人知道怎么做吗?</select></option> - How can I disable an <option> in a <select> based on its value in JavaScript? 如何使用jQuery在选择框选项中获取类的值 - how do I get the value of a class in the select box option with jquery 如何在输入文本字段中获取选择框选项值 - How to get select box option value in a input text field 如何获取此选项框的值并将其放在javascript变量中 - how to get value of this option box and put it in javascript variable 隐藏一个选项(如果在另一个选择框中选中了该选项) - Hiding an option if its selected in the other select box JavaScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM