Sowmya
Sowmya

Reputation: 473

How to ignore case (upper/lower) while triggering change for select in jquery?

Please see the code below:

<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<select>
<option>one</option>
<option>two</option>
<option>three</option>
<option>four</option>
<option>five</option>
</select>
<script>
$("select").val("TWO").trigger("change");
</script>
</body>
</html>

In this case option is not set with the value "TWO" . But if I change as :

$("select").val("two").trigger("change");

Then it works. How can I ignore case while triggering change for select?

Upvotes: 1

Views: 298

Answers (4)

Chetan Joshi
Chetan Joshi

Reputation: 349

Use Regular Expression

$("select option").each(function(){
 if(this.value.match(/TWO/i)){
     $(this).attr("selected","selected")
 }
});
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<select>
<option>one</option>
<option>two</option>
<option>three</option>
<option>four</option>
<option>five</option>
</select>

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82251

You need to get select option by text and then set it as selected:

 $('select option').filter(function () { 
   return $(this).text().toLowerCase() == 'two'; 
 }).prop('selected', true);    

$('select option').filter(function () { 
   return $(this).text().toLowerCase() == 'two'; 
 }).prop('selected', true);   
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option>one</option>
<option>two</option>
<option>three</option>
<option>four</option>
<option>five</option>
</select>

Upvotes: 0

Karthikeyan Vedi
Karthikeyan Vedi

Reputation: 1360

Try this - This will ignore cases

  var optionVal = $('select option').filter(function() {
    return this.value.toLowerCase() == 'two';
  }).val();

  $("select").val(optionVal).trigger("change");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select>
  <option>one</option>
  <option>Two</option>
  <option>three</option>
  <option>four</option>
  <option>five</option>
</select>

Upvotes: 1

Coder
Coder

Reputation: 240

$("select").val("TWO".toLowerCase()).trigger("change");

make all value in lowercase and now you able to check not matter upper or lower case in string

Upvotes: 0

Related Questions