some jQuery/javascript help. Add items to optgroup

Hcabnettek picture Hcabnettek · Oct 9, 2009 · Viewed 7.6k times · Source

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

Answer

Russ Cam picture Russ Cam · Oct 9, 2009

Firstly,

$(this).appendTo($(groups[1]));

can be changed to

$(this).appendTo(groups[1]);

you don't need to wrap the element again into a jQuery object in order to append to it, a HTMLElement will work fine.

Do you have the HTML that you're using and where are your <option> elements that you are checking the value of?

EDIT:

I've rewritten your code slightly and this works correctly (N.B. appending won't work in IE6 and I believe 7 and 8 too - In IE the innerHTML property for a select element is readonly, so use createElement or the Option constructor to create options),

Working Example. add /edit to the URL to see the code. I have the option elements in an array in the working example, I assume that you have them in a similar structure.

var groups = $("optgroup");
$('options').each(function() {
    var $this = $(this);
    var val = $this.val();
    if (tmp.indexOf(val) !== -1) {
        $this.appendTo(groups[0]);
    } 
    else if (val.length > 0) {
        $this.appendTo(groups[1]);
    }
});