Reputation: 85308
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>
Upvotes: 1
Views: 3860
Reputation: 59271
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();
});
Upvotes: 8
Reputation: 40052
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.
Upvotes: 1
Reputation: 41381
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());
});
Upvotes: 1