humbolight
humbolight

Reputation: 690

jQuery.append() ignores element in htmlstring

Just curious if anyone has insight into this jQuery behavior, which seems buggy to me.

I have an empty select form element that I want to append options to, one of which is hidden by wrapping it in a span element with display style set to none.

snippet 1 - appends the options but ignores the span element:

var myOptions = '<option value="1">1</option><span style="display:none;"><option value="2">2</option></span>';
$('#mySelect').append(myOptions);

snippet 2 - works as intended:

var myOptions = '<option value="1">1</option><option value="2">2</option>';
$('#mySelect').append(myOptions);
$('#mySelect').find('options:eq(1)').wrap('<span style="display:none;"/>');

Upvotes: 0

Views: 118

Answers (2)

Kevin B
Kevin B

Reputation: 95023

Don't append the option you want to hide, instead store it on the select.

var myOptions = $.parseHTML('<option value="1">1</option><option value="2">2</option>');
$('#mySelect').append(myOptions.eq(0)).data("hiddenOptions",myOptions.eq(1));

Now if you wanted to add it back, it's conveniently stored on the select's data object.

$("#mySelect").data("hiddenOptions").appendTo("#mySelect")

Upvotes: 0

Brad M
Brad M

Reputation: 7898

The only valid child elements for <select> is <option> and <optgroup> (courtesy of Marcell)

Upvotes: 4

Related Questions