Bryan Denny
Bryan Denny

Reputation: 27596

JQuery: How do I select a value from a dropdownlist case insensitive?

My scenario:

This works perfectly fine if the textbox value is the same case as the dropdownlist value. But I want it to be case insensitive.

So if the user types "stackoverflow" then I want it to select from the dropdownlist "StackOverflow". How can I do this via jQuery?

Upvotes: 13

Views: 9430

Answers (4)

Patrick McElhaney
Patrick McElhaney

Reputation: 59331

Here's another approach: find the matching value in its actual case, "StackOverflow," and call val() with that.

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

Of course, the literal 'stackoverflow' should be replaced with a variable.

Upvotes: 20

Scharrels
Scharrels

Reputation: 3065

On blur, iterate over your options and check if it matches. Then select the one that matches.

In code:

$("#button").blur(function(){
  var val = $(this).val();
  $("#list option").each(function(){
     if($(this).text().toLowerCase() == val) $(this).attr("selected","selected");
  });
});

I didn't test it yet, so be sure to check for syntax errors.

Upvotes: 2

Anwar Chandra
Anwar Chandra

Reputation: 8648

The regular expression (RegExp) function is probably the way to go.

var txt = new RegExp(pattern,attributes);

pattern: the text pattern
attributes: "i" for case-insensitive

You can combine with filter function. something like this should work.

$("#textbox").blur( function () { 

    var text = $(this).val();

    var dropdownlist = 
       $("select").filter( function () {
          return (new RegExp(text, "i")).test($(this).attr("id"));
       });

    // do something to dropdownlist

});

Upvotes: 0

Tyler Carter
Tyler Carter

Reputation: 61577

I think that the best way to do this is look at it from the before rather than the after. If you make them all lowercase, they are all standardized and easier to work with. Then all you have to do is make the user's input all lowercase, and it is really easy to match stuff.

Another option is to use a filter function, like the one found here:

$('something').filter(function() {
        return (new RegExp(value, "i")).test($(this).attr('attribute'));
    });

Value and attribute need to be replaced though.

Upvotes: 4

Related Questions