Search code examples
javascriptjquerydrop-down-menuhtml-selectoptgroup

some jQuery/javascript help. Add items to optgroup


I have an array called tmp

var tmp = ["05", "13", "27"];

if an option value is equal to a value within tmp, I want to add that option to a particular optgroup, else add it to the other optgroup. I keep getting everything added to optgroup #2, except the option with the value "27". What am I doing incorrectly?

    var groups = $("optgroup");
    $("option").each(function() {
        var value = $(this).val();
        for (var x = 0; x < tmp.length; x++) {
            var isMatch = (tmp[x] === value);
            if (isMatch) {
                $(this).appendTo($(groups[0]));
            } else if (value.length > 0) {
                $(this).appendTo($(groups[1]));
            }
        }

    });

Thanks for any pointers to correct this.

~ck in San Diego


Solution

  • You should add a break after each appendTo statement so that you don't keep comparing the option to all tmp values.

    var groups = $("optgroup");    
        $("option").each(function() {        
           var value = $(this).val();        
           for (var x = 0; x < tmp.length; x++) {            
                var isMatch = (tmp[x] === value);            
                if (isMatch) {                
                      $(this).appendTo($(groups[0]));            
                      break;
                } else if (value.length > 0) {                
                      $(this).appendTo($(groups[1]));            
                      break;
                }        
           }    
        });