简体   繁体   English

Javascript从基于标签的选择选项中获取价值

[英]Javascript get value from select option based on label

Using either jQuery or pure JavaScript, how can I get the ID for a select option based on the label? 使用jQuery或纯JavaScript,如何基于标签获取选择选项的ID? So for example, given the following: 因此,例如,给出以下内容:

<select id="blah">
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
</select>

If I have the label "Two" but I need to know the value associated with it, how can I get that value from this select? 如果我有标签“ Two”,但是我需要知道与之关联的值,那么如何从选择中获得该值? I don't want to simply select it, I need to know what the value is. 我不想简单地选择它,我需要知道值是什么。

If the only reference you have is really the actual text content, then you'll have to loop through the elements and check the content of each one. 如果您拥有的唯一参考确实是实际的文本内容,那么您将不得不遍历元素并检查每个元素的内容。 Shown here with jQuery just because it's less to type: 此处显示的是jQuery,因为它的类型更少:

var result;
$("option").each(function() {
    if ($(this).text() == "Two") {
        result = $(this).attr("value");
        return false;
    });
});

Another option: 另外一个选项:

$('#blah').find('option:contains("Two")').val();

(Pun intended?) (双关打算吗?)

Get all the options and then use find to get the one with specific text. 获取所有选项,然后使用find获得带有特定文本的选项。

 const optionEls = Array.from(document.querySelectorAll("#blah option")); const hasText = text => el => el.textContent === text; const optionWithTwo = optionEls.find(hasText("Two")); console.log(optionWithTwo.value); 
 <select id=blah> <option value=1>One</option> <option value=2>Two</option> <option value=3>Three</option> </select> 

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM