Santhucool
Santhucool

Reputation: 1726

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

Upvotes: 1

Views: 602

Answers (3)

keipa
keipa

Reputation: 792

If you want to select the element with exact text use Regex

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

Upvotes: 1

Mamdouh Saeed
Mamdouh Saeed

Reputation: 2324

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>

Upvotes: 3

Andy Tschiersch
Andy Tschiersch

Reputation: 3815

You can use .html() to check content:

$('#lang option').each(function() {
  if ($(this).html() == 'java') {
    alert($(this).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>

Upvotes: 2

Related Questions