Can I get Select box value from given select box text

时间:2015-04-24 21:27:18

标签: javascript jquery html

Can I get Select box value from given select box text ? Need help

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

$("#list[text='Option B']").val();

3 个答案:

答案 0 :(得分:4)

Try

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

Edit, Updated

As pointed out by @dfsq , commenting on original answer

Not very reliable, as it will also much "Option Boom". filter might be better option.

tests http://jsfiddle.net/5cy9tt2o/1/

Additionally,

because :contains selector just checks indexOf for occurrences. See the source of it here. ... usually it's not a problem, just > something to be aware of.

where ":contains selector just checks indexOf for occurrences" does not appear at documentation ?


Utilizing .filter() may also return "unreliable" results if a particular match is found, or not found , by the provided match to search for within the given element text.

For example, @dfsq provided the example of

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

matching

"Option Boom"

The accepted answer , though utilizing .filter() may not return expected results if " " appeared after text

<option value='2'>Option B </option>

tests http://jsfiddle.net/5cy9tt2o/4/


An alternative approach, which should be expected to return exact match , without calling addition internal methods ; though passing RegExp parameters, or any other settings , could , of course, be optional.

Basic and primary focus of method to return exact match, if that is possible, of text passed to the method.

Given html from original post, modified with same test conditions tried at above,

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

js

(function($) {
  $.fn.tryToMatchExactText = function (text) {
    return $("*").filter(function(i, el) {
      return el.textContent.match(new RegExp("^"+text+"$")) !== null
    })
  };
}(jQuery));

var list = $("#list option");

console.log(list.tryToMatchExactText("Option B").val() // `"2"`
       , list.tryToMatchExactText("Option Boom").val() // `"1"`
       , list.tryToMatchExactText("Option C").val() // `undefined`
       , list.tryToMatchExactText("Option C ").val() // `"3"`
);

tests http://jsfiddle.net/5cy9tt2o/3/

答案 1 :(得分:4)

You can use filter:

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

You could also use $("#list option:contains(Option B)"), but it would bring multiple results in your case.

答案 2 :(得分:0)

Go For :

$("#list").children().eq(2).val();