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
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;
}
}
});
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]);
}
});
精彩评论