I have a HTML select like this:
<select name="something">
<option value="a">1</option>
<option value="b">2</option>
<option value="c">3</option>
</select>
and I've noticed that jquery interprets that options are hidden HTML tags. The problem comes when I have to remove real hidden tags like in this example:
<form action="#" id="f">
<select name="something">
<option value="a">1</option>
<option value="b">2</option>
<option value="c">3</option>
</select>
<p style="display:none">hello world</p>
<any_tag style="display:none">some text</any_tag>
</form>
If I execute this:
$("#f :hidden").remove();
all options are removed. The question is why jquery removes options? and what is the most appropriate selector to remove only hidden tags? (well or not option tags)
Here is a test .
Source: Tips4all
You could just add the functionality that should already be there :P
ReplyDelete$("#f :hidden:not(option)").remove();
Check out this jQuery bug report: http://bugs.jquery.com/ticket/6293
ReplyDeleteOf particular note:
Changed 3 months ago by john
Status changed from open to closed
Resolution set to wontfix
Considering that every browser but Firefox
says that it's hidden - it seems like it's the other way around. That
being said, I'm not really sure what you're trying to achieve with
:hidden/:visible on option elements. It seems like you should probably
be using :selected instead. Don't think this is something that we're
going to spend a lot of cycles on.
As a fix for this case, I'd go for what @Joseph has already provided:
$("#f :hidden:not(option)").remove();
..which works as intended: http://jsfiddle.net/thirtydot/G4Qnr/4/
Try:
ReplyDelete$(":hidden").not("option")
In this case, you could simply wrap the hidden elements in a container of some sort, and use jQuery to remove the elements from the container:
ReplyDelete<div id="foo">
<p style="display:none;">hello world</p>
</div>
Then, in jQuery you can just do this:
$("#foo :hidden").remove();
EDIT
Here's another approach:
$("#f :hidden").not("option").remove();
Not sure about the why, but you can remedy by using the :not jQuery selector.
ReplyDelete$("#f :not(option):hidden").remove();
http://jsfiddle.net/G4Qnr/2/