Naruto
Naruto

Reputation: 9634

Hide list item in jquery

I want to hide list item in jquery, but its getting failed if i do like this,

$(Name + "-myList option[value=" + selectedItem + "]").hide(); //fails

But how come these two options disable and remove works:

$(Name + "-myList option[value=" + selectedItem + "]").attr("disabled", "disabled");

$(Name + "-myList option[value=" + selectedItem + "]").remove();

Here is my list code

<select id="myList" class="DropDownList Test" name="List">                                           
    <option value="selectid" selected="selected">--Please Select--</option> 
    <option value="test1">a</option> 
    <option value="test2">b</option> 
    <option value="test3">c</option>               
</select>

Upvotes: 1

Views: 797

Answers (2)

PassKit
PassKit

Reputation: 12581

.hide() will not hide the item because .hide() works by adding the inline css display:none to the element. Almost all browsers do not allow an option element to be styled.

Disabling the option will not remove or hide the option, but will make it appear greyed out and unavailable for selection. The disabled attribute can be easily toggled if you need to re-enable the option later..

remove() completely removes the element from the DOM, so if you use this approach you will need to recreate it with $('#mylist').append( new Option('text','value')); in order to display it again.

Upvotes: 2

Jason Evans
Jason Evans

Reputation: 29186

You can use the jQuery :selected selector like so:

$(Name + "-myList option :selected").attr("disabled", "disabled");
$(Name + "-myList option :selected").remove();

This will make getting the selected item easier.

As for hiding the item, looks like @PassKit has explained why .hide() will not work.

Upvotes: 1

Related Questions