Hide select option in IE using jQuery

2019-01-02 15:53发布

Currently I am using jQuery to hide/show select options using following code.

$("#custcol7 option[value=" + sizeValue + "]").hide();

This works fine in Firefox, but doesnt do any good in other browsers. How to I hide options from select in Chrome, Opera and IE?

17条回答
不再属于我。
2楼-- · 2019-01-02 16:15

You will need to remove it and then add it again for Internet Explorer.

To remove:

$("#custcol7 option[value=" + sizeValue + "]").remove();

To add:

$("#custcol7").append( "<option value='sizeValue'>sizeValue</option>" );

Note that you need to have sizeValue also in the option text, to actually see something.

查看更多
余生无你
3楼-- · 2019-01-02 16:16

the way you did it should work in chrome but nvm.Here is another way

select = $('#custcol7');
select.find('option[value=["'+sizeValue +'"]').remove();

and if you want to show it again:

select.append('<option value="'+sizeValue+'"></option>');

It works perfectly on every browser and its really simple code. The problem is if you want to hide several options it is more typing .. but that can be solved by putting them into variables if they don't change dynamically like that :

var options = '<option value="'+sizeValue1+'"></option><option value="'+sizeValue2+'"></option><option value="'+sizeValue3+'"></option>';

select.append(options);

This way if you have to remove/append on several places you only typed the options once.Hope i gave another interesting option. Best Regards.

查看更多
浪荡孟婆
4楼-- · 2019-01-02 16:18

You don't, it's not supported in IE (and assumably not in Chrome or Opera either). You would have to remove the options altogether and add them back later if you want them to be truly invisible. But in most cases a simple disabled="disabled" should suffice and is a heck of a lot simpler than handling the removing and adding of options.

查看更多
不流泪的眼
5楼-- · 2019-01-02 16:18

try detach(). you can reattach it later if needed using append() or insertAfter()

查看更多
若你有天会懂
6楼-- · 2019-01-02 16:18
/**
* Change visibility of select list option elements
* @param  {boolean}   stateVal      show hidden options if true; hide it otherwise. If not setted then toggle visibility, based on it's current state
*/
$.fn.toggleOptionVisibility = function (stateVal) {
    var isBool = typeof stateVal === "boolean";
    return this.each(function () {
         var $this = $(this);
         if (isBool) {
             if (stateVal) $this.filter("span > option").unwrap();
             else $this.filter(":not(span > option)").wrap("<span>").parent().hide();
         }
         else {
             $this.filter("span > option").toggleOptionVisibility(true);
             $this.filter(":not(span > option)").toggleOptionVisibility(false);
        }
    });
};
查看更多
永恒的永恒
7楼-- · 2019-01-02 16:21

In IE 11(Edge), the following code is working.

 $("#id option[value='1']").remove();

and to ad back,

$('<option>').val('1').text('myText').appendTo('#id');
查看更多
登录 后发表回答