0

I'm trying to set a selected value on a dropdown. But before I do this I check if the selected value is present within the control. To do this I use the following code:

var exists = 0 != $('#comp option[value="'+ value +'"]').length; 

where value can be upper, lower case or mixed case. How can I rewrite this bit of code so it works with all sorts of casing?

4 Answers 4

2

Instead of selecting for all just make the value to lower case when checking it.

value.toLowerCase();
2
  • The values in the list are not lower case and I can't make them in this scenario.
    – Patrick
    Apr 19, 2012 at 14:57
  • But can you make them lower case just to check the values? These don't have to change the values. Apr 19, 2012 at 15:02
1
$('#comp option').each(function() {
   if(this.value.toLowerCase() === value.toLowerCase() ) { 
      // do something
   }
});
1
  • np. I would suggest maybe looking to see if there was a more performant solution to this. if this is the only form on your page, or it is named.. you can eliminate jQuery completely.
    – rlemon
    Apr 19, 2012 at 15:18
0
var myvalue = 'ONE';
$('select option').filter(function() {
    if(new RegExp(this.value, 'ig').test(myvalue))
        $(this).attr('selected', true);
});
0

Also you can use this approach.

var matchingValue = $('#select option').filter(function () { 
     return this.value.toLowerCase() == 'stackoverflow'; 
     } ).attr('value');    
$('#select').val(matchingValue);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.