tags:

views:

739

answers:

3

Ok I have a drop down of countries and only want to display USA and Canada

I'm looking at something like this but don't think I'm doing this right

// Filter Countries
$('#selectId').filter(function() {
   return $('#option').val() == ('USA' || 'CANADA');   
});

Example HTML:

<select id="country">
  <option value="AFG">Afghanistan</option>
  <option value="ALB">Albania</option>
  <option value="ALG">Algeria</option>
  <option value="CANADA">Canada</option>
  <option value="USA">United States</option>
</select>
+7  A: 

The || construct you have is invalid. Try this.

$(this).val() == 'USA' || $(this).val() == 'CANADA';


To remove the options that don't match, you could do something like this.

$().ready( function () {
  $('#country option').filter(function() {             
     return !($(this).val() == 'USA' || $(this).val() == 'CANADA');   
  }).remove();
});
Patrick McElhaney
The hide() method doesn't seem to work for option elements in my testing. Running your code didn't work for me. You might wanna double check.
Gabriel Hurley
Thanks this help and worked :)
Phill Pafford
np. it's an all-around good answer now.
Gabriel Hurley
Thanks, Gabriel. The first solution I posted simply hid the non-matching options. That works in FireFox, but I'm not sure if works anywhere else. Updated the code so that it actually removes the non-matching options.
Patrick McElhaney
+1  A: 

Alternatively, if you have a lot of items in your list you want to filter against, or you want to change the items you are filtering for, use this:

// define this anywhere
Array.prototype.inArray = function (value) {
    var i;
    for (i=0; i < this.length; i++) {
     if (this[i] === value) {
      return true;
     }
    }
    return false;
};

// your choice on how to provide this list, I'm using
// something simple as an example
var want = ['USA', 'CANADA'];

// now, somewhere, this filter happens
$('#selectId').filter(function() {
   return want.inArray($('#option').val());   
});
altCognito
+1  A: 

There's several problems there... you need to use the proper selector #country, filter only returns objects, it doesn't actually act on them... the compound OR syntax there doesn't work in JS...

This works (tested):

$('#country').children().each(function() {
   if ($(this).val() != 'USA' && $(this).val() != 'CANADA') $(this).remove();   
});

You have to use the remove() method because hide() won't do the trick for option elements.

Gabriel Hurley