0

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;"/>');
3
  • 2
    probably because it's invalid HTML. Why not set display:none directly to option? Commented Jun 13, 2013 at 16:52
  • styling the option to display:none doesn't hide it in IE ... that's exactly what I was doing until it was tested in IE Commented Jun 13, 2013 at 16:59
  • An option could be to remove it and append it back. Commented Jun 13, 2013 at 17:06

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I was thoroughly confused.
0

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")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.