简体   繁体   English

如何在触发jquery中的select更改时忽略大小写(大写/小写)?

[英]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" . 在这种情况下,选项未设置为值“ 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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