简体   繁体   中英

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?

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> 

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

将所有值都转换为小写,现在您可以检查字符串中的大小写无关紧要

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> 

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM