Santhucool Santhucool - 25 days ago 6
jQuery Question

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

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

Answer

Example using .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>

Comments