1

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?

Sowmya
  • 453
  • 1
  • 5
  • 18

4 Answers4

1

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>
Karthikeyan Vedi
  • 1,360
  • 1
  • 11
  • 17
  • Doesn't exactly *ignore case*. What if it was: `` ? – freedomn-m Aug 24 '16 at 07:06
  • toLowerCase() will work. But here it should work by ignoring the case. As I will not be aware the case from the option list. It is dynamic , sometimes capital and sometimes small. For example when I pass "TWO".toLowerCase() , if the option list contains "TWO" then it will not work . – Sowmya Aug 24 '16 at 07:06
  • I have update the answer, it will ignore cases. Just be sure to pass lowercase value for testing @ `return this.value.toLowerCase() == 'two';` here value `two` must be in lowercase, it can be in any case in the select option – Karthikeyan Vedi Aug 24 '16 at 07:16
0
$("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

Coder
  • 240
  • 2
  • 4
  • 20
0

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>
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
0

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>
Chetan Joshi
  • 339
  • 2
  • 5
  • 19