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?

sblundy
  • 60,628
  • 22
  • 121
  • 123
ninja
  • 183
  • 1
  • 12
  • 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(). – Robert Massa May 19 '10 at 13:24
  • Yea I understand that. My question is why hide() is not working on individual options. – ninja May 19 '10 at 14:04
  • http://stackoverflow.com/a/21085171/1544708 you may want to try this simple solution – William Herry Jan 13 '14 at 06:36

3 Answers3

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;
}
rmirabelle
  • 6,268
  • 7
  • 45
  • 42
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

Community
  • 1
  • 1
redsquare
  • 78,161
  • 20
  • 151
  • 159
  • 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. – ninja May 19 '10 at 14:03
  • x-browser = cross browser (chrome, ff, ie opera etc) – redsquare May 19 '10 at 15:47
-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/

meder omuraliev
  • 183,342
  • 71
  • 393
  • 434
  • unfortunately this dose not work with chrome, which does not recognise the span exists within the select – nodrog Jun 11 '12 at 17:15