1

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>
0

2 Answers 2

2

.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.

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

5 Comments

i just want to hide and show whenver i want, wat is the solution for it.. should i add display:none in my list creation in HTML?
display:none will never work. If you want to completely hide it then use remove() and then recreate the element when you want to show it again. $('#mylist').append( new Option('text','value')); should do the trick.
Hi Passkit, it would be great if u do me one help. i.e how can i insert at particular position. i.e if i have removed 2nd element then i want to put it back at 2nd position, could pls provide me sytax
remove is working but if i try to add nothing is getting displayed in list, pls help me :(
Have a look at this fiddle for a pointer on how to insert at the nth position. Without seeing your code it's impossible to tell why it is not working.
1

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.

1 Comment

@LLL Check @PassKit's answer, he explains why display:none does not work.

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.