简体   繁体   中英

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? 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? 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:

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.

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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