隐藏选择选项在IE中使用jQuery

时间:2022-08-24 11:13:36

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

目前,我使用jQuery来隐藏/显示使用以下代码的选择选项。

$("#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?

这在Firefox中工作得很好,但在其他浏览器中没有任何好处。如何在Chrome, Opera和IE中隐藏选项?

16 个解决方案

#1


43  

I just came across this and instead of cloning the entire select over and over I just replaced the options that need to be hidden with span elements and hiding the spans ( though the browser didnt visually show them anyway, I think ) - you may need to change your code ( if complex ) to iterate through the spans for complex logic.

我刚在这而不是克隆整个选择,我只是替换的选项需要隐藏在span元素和隐藏跨度(尽管浏览器没有直观地告诉他们,我认为),您可能需要更改代码(如果复杂)遍历复杂的逻辑的跨越。

The spans store a reference to the option and replace themselves with it when they need to be shown.

span存储对选项的引用,并在需要显示时用它替换它们。

This code can obviously be refactored and prettified.

显然,可以重构和美化这些代码。

http://fiddle.jshell.net/FAkEK/12/show/

http://fiddle.jshell.net/FAkEK/12/show/

EDIT #2 ( USE THIS INSTEAD ): It occurred to me that instead of doing all this clone/reference/replace crap, just wrap the option with a span, hide the span, and on show just replace the span with the option again..

编辑#2(改为使用这个):我突然想到,与其做所有这些克隆/引用/替换垃圾,不如用span包装选项,隐藏span,然后在show中再次用这个选项替换span。

http://fiddle.jshell.net/FAkEK/25/show/

http://fiddle.jshell.net/FAkEK/25/show/

#2


26  

I think meder has provided valid answer and here it is slightly changed to reflect what works for me:

我认为meder提供了有效的答案,这里稍微做了一些修改,以反映什么对我有效:

$.fn.optVisible = function( show ) {
    if( show ) {
        this.filter( "span > option" ).unwrap();
    } else {
        this.filter( ":not(span > option)" ).wrap( "<span>" ).parent().hide();
    }
    return this;
}

Tested with (long live BrowserStack):

测试用(长寿命的浏览器):

  • Windows XP: IE 6.0, Firefox 3.0, Safari 4.0, Opera 10.0, Chrome 14.0
  • Windows XP: IE 6.0,火狐3.0,Safari 4.0, Opera 10.0, Chrome 14.0
  • Windows 8: IE 10.0 Metro
  • Windows 8: IE 10.0 Metro
  • iOS 3.2 (iPad), iOS 6.0 (iPhone 5)
  • iOS 3.2 (iPad)、iOS 6.0 (iPhone 5)
  • Android 1.6 (Sony Xperia X10)
  • Android 1.6(索尼Xperia X10)

jsfiddle

jsfiddle

#3


10  

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.

你不需要,它在IE中不受支持(假设也不在Chrome或Opera中)。如果你想让这些选项真正不可见,你必须把它们全部删除,然后再添加回来。但是在大多数情况下,一个简单的disabled="disabled"就足够了,而且比处理选项的删除和添加要简单得多。

#4


9  

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

尝试分离()。如果需要,可以使用append()或insertAfter()

#5


5  

To Remove options use:

删除选择使用:

var opt=$("option").detach();

To show options use:

显示选择使用:

opt.appendTo( "select" );

#6


3  

Just deleted it and store it in a var in your JavaScript. You can just create the new object when you need it later.

只需删除它并将其存储在JavaScript的var中。您可以在稍后需要时创建新的对象。

Otherwise try the disabled attribute mentioned above.

否则,请尝试上面提到的禁用属性。

#7


2  

/**
* 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);
        }
    });
};

#8


2  

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

你的方法应该可以在chrome上运行,但是nvm。这是另一种方式

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.

这样,如果您必须删除/追加几个位置,您只需输入一次选项。希望我给了另一个有趣的选择。致以最亲切的问候。

#9


1  

There's also the the .load method:

还有。load方法:

s_parent.change(function(){
   s_child.load('./fetch_options.php",{'v',s_parent.val()});
}

The 'fetch_options.php' script would simply print the option tags based on whatever data source you use and the parent value(s) being passed in.

“fetch_options。php的脚本将基于您使用的任何数据源以及传入的父值打印选项标记。

#10


1  

My take is bit different to other answers.

我的看法和其他的答案有点不同。

The aim is not to hide the options but just make them disable(to keep the UI consistent).

目的不是隐藏选项,而是禁用它们(以保持UI的一致性)。

My Scenario :

我的情况:

I have multiple selects in a form and when an user selects an option in one of the selects the other selects should disable this option and vice versa. User is restricted from selecting the same option which is already selected. We normally disable the option but for IE 7 which does not support it. User also gets an option to add new selects.

我在表单中有多个选择,当用户在其中一个选择中选择一个选项时,另一个选择应该禁用这个选项,反之亦然。用户被限制选择已经被选择的相同选项。我们通常禁用选项,但IE 7不支持。用户还可以获得添加新选择项的选项。

Solution :

解决方案:

On load :

负载:

If the browser is IE7 then while populating the the selects and disabling the already selected options on other selects I am adding a custom attribute to the option("data-ie7-disabled") and also changing the color of the disabled options to '#cccccc'(which is the standard color for disabled options). This makes the UI look same across browsers.

如果浏览器是IE7,那么在填充选择和禁用已经选择的其他选项时,我将添加一个自定义属性到选项(“data-ie7-disabled”),并将禁用选项的颜色改为“#cccccc”(这是禁用选项的标准颜色)。这使得UI在浏览器之间看起来是一样的。

On Change :

在改变:

I save the previous option in a local variable(this is saved on focus).

我将前面的选项保存在一个局部变量中(这将保存在焦点上)。

When a user tries to change an option

当用户试图更改选项时

  1. User selects a complete new option which is not selected in any other dropdown. Then I loop through other selects and change the color and add custom attribute to this selected option on other selects.

    用户选择一个完整的新选项,该选项在任何其他下拉菜单中都没有被选择。然后我循环通过其他的选择和改变颜色,并在其他选择上添加自定义属性到这个选中的选项。

  2. When user selects an option that is already selected(The option which has grayed out color). I check if the option has this custom attribute on it first. If it has then > I simply revert the option to the previous one with an error message saying "This option is already selected or BLAH BLAH".

    当用户选择一个已经被选择的选项时(这个选项已经变灰)。我先检查选项是否有这个自定义属性。如果它有>,我只需将选项还原为前面的选项,并显示一条错误消息,说“这个选项已经被选中了,或者是诸如此类的东西”。

  3. When user changes his existing option to a brand new option which is not selected in any other dropdown's. I again loop through all the other select options and remove the color on it and also the custom attribute.

    当用户将其现有选项更改为一个全新的选项时,该选项在任何其他下拉菜单中都没有被选中。我再次循环所有其他的选择选项,并删除它的颜色和自定义属性。

Hope this helps.

希望这个有帮助。

#11


1  

You can use through combinations of var $opt=$('select>option').clone() and $('select option[value="'+val+'"').remove(). There is another example: try this. https://jsfiddle.net/sherali/jkw8fxzf/12/

可以通过var $opt=$('select>option').clone()和$('select option[value= ' ' '+val+' ' ']).remove()组合使用。还有另外一个例子:试试这个。https://jsfiddle.net/sherali/jkw8fxzf/12/

var $secondOption= $('#second-choice>option').clone();

$("#first-choice").change(function() {
    var userSelected = $(this).val();

    $('#second-choice').html($secondOption);
    $('#second-choice option[value="'+userSelected+'"').remove()
});

#12


0  

You can use this:

您可以使用:

$("#custcol7 option[value=" + sizeValue + "]").css({display:'none'});

It works fine on all browsers except Safari and Opera. I'm searching for another best solution :)

除了Safari和Opera,它在所有浏览器上都运行良好。我正在寻找另一种最好的解决办法:

#13


0  

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

您需要删除它,然后再添加它为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.

注意,您需要在选项文本中包含sizeValue,以便实际看到一些东西。

#14


0  

using the solution provided by AuthorProxy, it works fine for IE but when I attempt to do a .val() on the dropdown in firefox I get some funky values that don't make any sense. I have modified their option to include browser specific functionality, hide/show works for firefox.

使用AuthorProxy提供的解决方案,它对IE运行良好,但是当我尝试在firefox的下拉菜单上执行.val()时,我得到了一些没有任何意义的奇怪值。我修改了他们的选项,包括浏览器特定的功能,隐藏/显示工作为firefox。

$.fn.toggleOptionVisibility = function (stateVal) {
    var isBool = typeof stateVal === "boolean";
    return this.each(function () {
        var $this = $(this);
        if (navigator.userAgent.indexOf('MSIE') > -1 || navigator.userAgent.indexOf('Trident') > -1) {
            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);
            }   
        }
        else {              
            if (isBool) {
                $this.show();
            }
            else {
                $this.hide();
            }
        }
    });
};

#15


0  

You can also replace the html within the select.

您还可以在select中替换html。

Html:

Html:

<input id="Button1" type="button" value="hide option" />

<select id="foo">
<option >stuff</option>
<option >stuff2</option>
</select>

Jquery:

Jquery:

    $("#Button1").change(function () {
       $('#foo').html('<option >stuff</option>');
    });

Not exactly what you want, but perhaps it helps. For smaller dropdowns, it is definitely easier.

这并不是你想要的,但可能会有帮助。对于较小的下拉,肯定更容易。

#16


0  

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

在IE 11(Edge)中,以下代码正在工作。

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

and to ad back,

和广告,

$('<option>').val('1').text('myText').appendTo('#id');

#1


43  

I just came across this and instead of cloning the entire select over and over I just replaced the options that need to be hidden with span elements and hiding the spans ( though the browser didnt visually show them anyway, I think ) - you may need to change your code ( if complex ) to iterate through the spans for complex logic.

我刚在这而不是克隆整个选择,我只是替换的选项需要隐藏在span元素和隐藏跨度(尽管浏览器没有直观地告诉他们,我认为),您可能需要更改代码(如果复杂)遍历复杂的逻辑的跨越。

The spans store a reference to the option and replace themselves with it when they need to be shown.

span存储对选项的引用,并在需要显示时用它替换它们。

This code can obviously be refactored and prettified.

显然,可以重构和美化这些代码。

http://fiddle.jshell.net/FAkEK/12/show/

http://fiddle.jshell.net/FAkEK/12/show/

EDIT #2 ( USE THIS INSTEAD ): It occurred to me that instead of doing all this clone/reference/replace crap, just wrap the option with a span, hide the span, and on show just replace the span with the option again..

编辑#2(改为使用这个):我突然想到,与其做所有这些克隆/引用/替换垃圾,不如用span包装选项,隐藏span,然后在show中再次用这个选项替换span。

http://fiddle.jshell.net/FAkEK/25/show/

http://fiddle.jshell.net/FAkEK/25/show/

#2


26  

I think meder has provided valid answer and here it is slightly changed to reflect what works for me:

我认为meder提供了有效的答案,这里稍微做了一些修改,以反映什么对我有效:

$.fn.optVisible = function( show ) {
    if( show ) {
        this.filter( "span > option" ).unwrap();
    } else {
        this.filter( ":not(span > option)" ).wrap( "<span>" ).parent().hide();
    }
    return this;
}

Tested with (long live BrowserStack):

测试用(长寿命的浏览器):

  • Windows XP: IE 6.0, Firefox 3.0, Safari 4.0, Opera 10.0, Chrome 14.0
  • Windows XP: IE 6.0,火狐3.0,Safari 4.0, Opera 10.0, Chrome 14.0
  • Windows 8: IE 10.0 Metro
  • Windows 8: IE 10.0 Metro
  • iOS 3.2 (iPad), iOS 6.0 (iPhone 5)
  • iOS 3.2 (iPad)、iOS 6.0 (iPhone 5)
  • Android 1.6 (Sony Xperia X10)
  • Android 1.6(索尼Xperia X10)

jsfiddle

jsfiddle

#3


10  

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.

你不需要,它在IE中不受支持(假设也不在Chrome或Opera中)。如果你想让这些选项真正不可见,你必须把它们全部删除,然后再添加回来。但是在大多数情况下,一个简单的disabled="disabled"就足够了,而且比处理选项的删除和添加要简单得多。

#4


9  

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

尝试分离()。如果需要,可以使用append()或insertAfter()

#5


5  

To Remove options use:

删除选择使用:

var opt=$("option").detach();

To show options use:

显示选择使用:

opt.appendTo( "select" );

#6


3  

Just deleted it and store it in a var in your JavaScript. You can just create the new object when you need it later.

只需删除它并将其存储在JavaScript的var中。您可以在稍后需要时创建新的对象。

Otherwise try the disabled attribute mentioned above.

否则,请尝试上面提到的禁用属性。

#7


2  

/**
* 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);
        }
    });
};

#8


2  

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

你的方法应该可以在chrome上运行,但是nvm。这是另一种方式

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.

这样,如果您必须删除/追加几个位置,您只需输入一次选项。希望我给了另一个有趣的选择。致以最亲切的问候。

#9


1  

There's also the the .load method:

还有。load方法:

s_parent.change(function(){
   s_child.load('./fetch_options.php",{'v',s_parent.val()});
}

The 'fetch_options.php' script would simply print the option tags based on whatever data source you use and the parent value(s) being passed in.

“fetch_options。php的脚本将基于您使用的任何数据源以及传入的父值打印选项标记。

#10


1  

My take is bit different to other answers.

我的看法和其他的答案有点不同。

The aim is not to hide the options but just make them disable(to keep the UI consistent).

目的不是隐藏选项,而是禁用它们(以保持UI的一致性)。

My Scenario :

我的情况:

I have multiple selects in a form and when an user selects an option in one of the selects the other selects should disable this option and vice versa. User is restricted from selecting the same option which is already selected. We normally disable the option but for IE 7 which does not support it. User also gets an option to add new selects.

我在表单中有多个选择,当用户在其中一个选择中选择一个选项时,另一个选择应该禁用这个选项,反之亦然。用户被限制选择已经被选择的相同选项。我们通常禁用选项,但IE 7不支持。用户还可以获得添加新选择项的选项。

Solution :

解决方案:

On load :

负载:

If the browser is IE7 then while populating the the selects and disabling the already selected options on other selects I am adding a custom attribute to the option("data-ie7-disabled") and also changing the color of the disabled options to '#cccccc'(which is the standard color for disabled options). This makes the UI look same across browsers.

如果浏览器是IE7,那么在填充选择和禁用已经选择的其他选项时,我将添加一个自定义属性到选项(“data-ie7-disabled”),并将禁用选项的颜色改为“#cccccc”(这是禁用选项的标准颜色)。这使得UI在浏览器之间看起来是一样的。

On Change :

在改变:

I save the previous option in a local variable(this is saved on focus).

我将前面的选项保存在一个局部变量中(这将保存在焦点上)。

When a user tries to change an option

当用户试图更改选项时

  1. User selects a complete new option which is not selected in any other dropdown. Then I loop through other selects and change the color and add custom attribute to this selected option on other selects.

    用户选择一个完整的新选项,该选项在任何其他下拉菜单中都没有被选择。然后我循环通过其他的选择和改变颜色,并在其他选择上添加自定义属性到这个选中的选项。

  2. When user selects an option that is already selected(The option which has grayed out color). I check if the option has this custom attribute on it first. If it has then > I simply revert the option to the previous one with an error message saying "This option is already selected or BLAH BLAH".

    当用户选择一个已经被选择的选项时(这个选项已经变灰)。我先检查选项是否有这个自定义属性。如果它有>,我只需将选项还原为前面的选项,并显示一条错误消息,说“这个选项已经被选中了,或者是诸如此类的东西”。

  3. When user changes his existing option to a brand new option which is not selected in any other dropdown's. I again loop through all the other select options and remove the color on it and also the custom attribute.

    当用户将其现有选项更改为一个全新的选项时,该选项在任何其他下拉菜单中都没有被选中。我再次循环所有其他的选择选项,并删除它的颜色和自定义属性。

Hope this helps.

希望这个有帮助。

#11


1  

You can use through combinations of var $opt=$('select>option').clone() and $('select option[value="'+val+'"').remove(). There is another example: try this. https://jsfiddle.net/sherali/jkw8fxzf/12/

可以通过var $opt=$('select>option').clone()和$('select option[value= ' ' '+val+' ' ']).remove()组合使用。还有另外一个例子:试试这个。https://jsfiddle.net/sherali/jkw8fxzf/12/

var $secondOption= $('#second-choice>option').clone();

$("#first-choice").change(function() {
    var userSelected = $(this).val();

    $('#second-choice').html($secondOption);
    $('#second-choice option[value="'+userSelected+'"').remove()
});

#12


0  

You can use this:

您可以使用:

$("#custcol7 option[value=" + sizeValue + "]").css({display:'none'});

It works fine on all browsers except Safari and Opera. I'm searching for another best solution :)

除了Safari和Opera,它在所有浏览器上都运行良好。我正在寻找另一种最好的解决办法:

#13


0  

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

您需要删除它,然后再添加它为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.

注意,您需要在选项文本中包含sizeValue,以便实际看到一些东西。

#14


0  

using the solution provided by AuthorProxy, it works fine for IE but when I attempt to do a .val() on the dropdown in firefox I get some funky values that don't make any sense. I have modified their option to include browser specific functionality, hide/show works for firefox.

使用AuthorProxy提供的解决方案,它对IE运行良好,但是当我尝试在firefox的下拉菜单上执行.val()时,我得到了一些没有任何意义的奇怪值。我修改了他们的选项,包括浏览器特定的功能,隐藏/显示工作为firefox。

$.fn.toggleOptionVisibility = function (stateVal) {
    var isBool = typeof stateVal === "boolean";
    return this.each(function () {
        var $this = $(this);
        if (navigator.userAgent.indexOf('MSIE') > -1 || navigator.userAgent.indexOf('Trident') > -1) {
            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);
            }   
        }
        else {              
            if (isBool) {
                $this.show();
            }
            else {
                $this.hide();
            }
        }
    });
};

#15


0  

You can also replace the html within the select.

您还可以在select中替换html。

Html:

Html:

<input id="Button1" type="button" value="hide option" />

<select id="foo">
<option >stuff</option>
<option >stuff2</option>
</select>

Jquery:

Jquery:

    $("#Button1").change(function () {
       $('#foo').html('<option >stuff</option>');
    });

Not exactly what you want, but perhaps it helps. For smaller dropdowns, it is definitely easier.

这并不是你想要的,但可能会有帮助。对于较小的下拉,肯定更容易。

#16


0  

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

在IE 11(Edge)中,以下代码正在工作。

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

and to ad back,

和广告,

$('<option>').val('1').text('myText').appendTo('#id');