2

I have a select menu that is populated dynamically (via a Wordpress plugin) that I need to remove options that don't exist in my array values.

The items in the array will always need to be in my select menu.

I'm trying to do this by comparing the text value of the option. Here is what I have so far. Once I introduced the array I wasn't sure how to iterate through each option and compare against the array items.

jQuery("select[name*='vehicles'] > option").each(function() 
{
   var myGroups = ["Cars", "Bikes", "Airplanes", "Motorcycles"];

   jQuery.each(myGroups, function(index, value) {
      if(jQuery(this).text() != value) {
         jQuery(this).remove();
      }
   });
});
Brett Weber
  • 1,839
  • 18
  • 22
TJnTN
  • 57
  • 2
  • 9
  • you could use myGroups.indexOf(text) > -1 to determine if it is there, but this isn't supported in all versions of every browser. An extension covers the ones that don't support Array.prototype.indexOf() – Brett Weber Aug 21 '14 at 16:50
  • possible duplicate of [Javascript: Determine whether an array contains a value](http://stackoverflow.com/questions/1181575/javascript-determine-whether-an-array-contains-a-value) – Brett Weber Aug 21 '14 at 16:51

2 Answers2

3

You could try inArray for this:

jQuery("select[name*='vehicles'] > option").each(function() {
  var myGroups = ["Cars", "Bikes", "Airplanes", "Motorcycles"];
  if(jQuery.inArray(jQuery(this).text(), myGroups )===-1){
  jQuery(this).remove();
  }
});

Where -1 is returned if the text does not exist.

Wilfredo P
  • 4,070
  • 28
  • 46
  • 1
    Thank you Wilfredo P! I was unaware of inArray. Sometimes it's the simplist thing but you don't know it even exists. This worked...except since I am using .remove() I just need to change !==-1 to ==-1. – TJnTN Aug 21 '14 at 17:02
  • Shouldn't it be `===-1`? – SearchForKnowledge Jan 05 '18 at 17:44
1

Use, as suggested, jquery's inArray, or native JS indexOf

To make your code backwards compatible in the case you use indexOf, you have to define it where it isn't defined:

if(!Array.prototype.indexOf) 
{
    Array.prototype.indexOf = function(sSearchVal) 
    {
        for(var i = 0; i < this.length; i++) {
            if(this[i] === sSearchVal) {
                return i;
            }
        }
        return -1;
    };
}

and to use for your case :

if (myGroup.indexOf(text) > -1) { /* value exists in the array */ }
Brett Weber
  • 1,839
  • 18
  • 22