views:

632

answers:

4

My scenario:

  • I have a textbox that the user enters text
  • The textbox has an onblur function that tries to select a value from a dropdownlist (if it exists) based on the textbox input

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?

+3  A: 

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.

Chacha102
+1  A: 

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.

Scharrels
+2  A: 

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.

Patrick McElhaney
Thanks, this worked just the way I wanted it to!
Bryan Denny
A: 

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

});
Anwar Chandra