dropdown get option value using option text using contains method jquery returns wrong value

时间:2016-11-09 06:52:31

标签: jquery option dropdown

I have a dropdown as follows:

<select id="lang" >
       <option value="1">php</option>
       <option value="2">java j2ee</option>
        <option value="3">asp</option>
       <option value="4">java</option>
  </select>

What I am doing is trying get the option value using option text as follows;

Suppose java is option text so what I tried is as follows:

var a = $('#lang option:contains("java")').val();

But I am getting option value as 2 instead of 4 (which is correct and expected)

I am getting wrong because I am trying method contains. Please guide me how can I get exact value?

FIDDLE

3 个答案:

答案 0 :(得分:3)

使用.filter()

的示例

alert($('#lang option').filter(function(){return $(this).text() == 'java' }).val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="lang">
  <option value="1">php</option>
  <option value="2">java j2ee</option>
  <option value="3">asp</option>
  <option value="4">java</option>
</select>

答案 1 :(得分:2)

您可以使用.html()检查内容:

&#13;
&#13;
$('#lang option').each(function() {
  if ($(this).html() == 'java') {
    alert($(this).val());
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="lang">
  <option value="1">php</option>
  <option value="2">java j2ee</option>
  <option value="3">asp</option>
  <option value="4">java</option>
</select>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

如果要选择具有精确文本的元素,请使用Regex

var regex = new RegExp("^java$");
var a = $('#lang option').filter(function () {
    return regex.test($(this).text()); 
}).val();
alert(a);