5

I have a select lists, which has lots of option. Depending on some input I want to hide few options from select list. To hide options from select list I have written jquery like

$('#selectlist1 option').each(function(){ $(this).hide(); }) 

But this code seems to work only for firefox and its not working on chrome and ie. Whereas if I write

$('#selectlist1').hide(); 

it works for all browser. Any pointer where should I look at?

3
  • The difference is you're trying to hide individual option elements as opposed to the complete select element. Hide() also might not be the correct method here, try Remove(). Commented May 19, 2010 at 13:24
  • Yea I understand that. My question is why hide() is not working on individual options. Commented May 19, 2010 at 14:04
  • stackoverflow.com/a/21085171/1544708 you may want to try this simple solution Commented Jan 13, 2014 at 6:36

3 Answers 3

2

Here's a relatively concise way to rebuild the select list on demand with new options. This works for dynamically inserted options (which is what IE and Chrome have a problem with showing and hiding)

$().ready(function() { //store a reference var select = $('#myselect'); }); function rebuild_select(arr_new_options) { var parent = select.parent(); select.empty(); var clone = select.clone(); select.remove(); for(var x=0; x < arr_new_options.length; x++) { clone.append(arr_new_options[x]); } parent.append(clone); select = clone; } 
Sign up to request clarification or add additional context in comments.

Comments

1

You cannot hide individual option elements x-browser. The only solution is to replace the select with a new element with only the options you wish to display.

See this other question

2 Comments

What do you mean by 'x-browser'? I tried the solution suggested by you. the problem is that I am using drupal and it store some data in cache to verify form structure. So if I remove some element and add them later, it gives error during validation. So i thought using show/hide method of jquery I can do that without any validation error. But it seems this is not supported in any browser other than mozilla.
x-browser = cross browser (chrome, ff, ie opera etc)
-2

For anyone having to deal with hiding option elements in those versions affected, I posted a workaround here which doesn't clone or remove the options but wraps spans around them, which is arguably much easier to deal with:

http://work.arounds.org/issue/96/option-elements-do-not-hide-in-IE/

1 Comment

unfortunately this dose not work with chrome, which does not recognise the span exists within the select

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.