使用jQuery在选择列表中隐藏选项。

时间:2022-12-02 18:13:52

I have an object with key/value pairs of options I want to hide/remove from a select list. Neither of the following option selectors work. What am I missing?

我有一个对象,有键/值对的选项,我想要隐藏/从一个选择列表中删除。以下选项都不是选择器工作的。我缺少什么?

$.each(results['hide'], function(name, title) {                     
  $("#edit-field-service-sub-cat-value option[value=title]").hide();
  $("#edit-field-service-sub-cat-value option[@value=title]").hide();
}); 

21 个解决方案

#1


100  

For what it's worth, the second form (with the @) doesn't exist in jQuery 1.3. The first isn't working because you're apparently expecting variable interpolation. Try this:

对于它的价值,第二个表单(@)不存在于jQuery 1.3中。第一个是无效的,因为显然你期望的是变量插值。试试这个:

$("#edit-field-service-sub-cat-value option[value=" + title + "]").hide();

Note that this will probably break in various hideous ways if title contains jQuery selector metacharacters.

注意,如果标题包含jQuery选择器元字符,那么它可能会以各种可怕的方式中断。

#2


80  

You cannot do this x-browser. If I recall ie has issues. The easiest thing to do is keep a cloned copy of the select before you remove items, this allows you to easily remove and then append the missing items back.

你不能做这个x-浏览器。如果我记得ie有问题。最简单的做法是在删除条目之前保留select的克隆副本,这样可以轻松删除并将丢失的项追加到后面。

#3


47  

Here is my spin, likely a bit faster due to native DOM methods

这是我的自旋,可能是由于本地DOM方法更快一些。

$.each(results['hide'], function(name, title) {                     
    $(document.getElementById('edit-field-service-sub-cat-value').options).each(function(index, option) {
      if( option.value == title ) {
        option.hidden = true; // not fully compatible. option.style.display = 'none'; would be an alternative or $(option).hide();
      }
    });
});

#4


47  

I found a better way, and it is very simple:

我找到了一个更好的方法,而且很简单:

$("option_you_want_to_hide").wrap('<span/>')

To show again, just find that option(not span) and $("option_you_want_to_show").unwrap().

要再次显示,只需找到该选项(不是span)和$("option_you_want_to_show").unwrap()。

It was tested on Chrome and Firefox.

它在Chrome和Firefox上进行了测试。

#5


12  

It CAN be done cross browser; it just takes some custom programming. Please see my fiddle at http://jsfiddle.net/sablefoste/YVMzt/6/. It was tested to work in Chrome, Firefox, Internet Explorer, and Safari.

可以跨浏览器完成;它只需要一些自定义编程。请参阅我的小提琴在http://jsfiddle.net/sablefoste/yvmzt/6/。它在Chrome、Firefox、Internet Explorer和Safari上进行了测试。

In short, I have a hidden field, #optionstore, which stores the array sequentially (since you can't have Associative Arrays in JavaScript). Then when you change the category, it parses the existing options (first time through only) writes them to #optionstore, erases everything, and puts back only the ones associated with the category.

简而言之,我有一个隐藏的字段#optionstore,它按顺序存储数组(因为在JavaScript中不能有关联数组)。然后,当您更改类别时,它会解析现有选项(第一次只通过)将它们写入#optionstore,删除所有内容,并只返回与该类别相关的选项。

NOTE: I created this to allow different option values from the text displayed to the user, so it is highly flexible.

注意:我创建这个是为了让文本显示给用户不同的选项值,所以它非常灵活。

The HTML:

HTML:

<p id="choosetype">
    <div>
        Food Category:
    </div>
    <select name="category" id="category" title="OPTIONAL - Choose a Category to Limit Food Types" size="1">
        <option value="">All Food</option>
        <option value="Food1">Fruit</option>
        <option value="Food2">Veggies</option>
        <option value="Food3">Meat</option>
        <option value="Food4">Dairy</option>
        <option value="Food5">Bread</option>
    </select>
    <div>
        Food Selection
    </div>
    <select name="foodType" id="foodType" size="1">
        <option value="Fruit1" class="sub-Food1">Apples</option>
        <option value="Fruit2" class="sub-Food1">Pears</option>
        <option value="Fruit3" class="sub-Food1">Bananas</option>
        <option value="Fruit4" class="sub-Food1">Oranges</option>
        <option value="Veg1" class="sub-Food2">Peas</option>
        <option value="Veg2" class="sub-Food2">Carrots</option>
        <option value="Veg3" class="sub-Food2">Broccoli</option>
        <option value="Veg4" class="sub-Food2">Lettuce</option>
        <option value="Meat1" class="sub-Food3">Steak</option>
        <option value="Meat2" class="sub-Food3">Chicken</option>
        <option value="Meat3" class="sub-Food3">Salmon</option>
        <option value="Meat4" class="sub-Food3">Shrimp</option>
        <option value="Meat5" class="sub-Food3">Tuna</option>
        <option value="Meat6" class="sub-Food3">Pork</option>
        <option value="Dairy1" class="sub-Food4">Milk</option>
        <option value="Dairy2" class="sub-Food4">Cheese</option>
        <option value="Dairy3" class="sub-Food4">Ice Cream</option>
        <option value="Dairy4" class="sub-Food4">Yogurt</option>
        <option value="Bread1" class="sub-Food5">White Bread</option>
        <option value="Bread2" class="sub-Food5">Panini</option>
    </select>
    <span id="optionstore" style="display:none;"></span>
</p>

The JavaScript/jQuery:

JavaScript / jQuery:

$(document).ready(function() {
    $('#category').on("change", function() {
        var cattype = $(this).val();
        optionswitch(cattype);
    });
});

function optionswitch(myfilter) {
    //Populate the optionstore if the first time through
    if ($('#optionstore').text() == "") {
        $('option[class^="sub-"]').each(function() {
            var optvalue = $(this).val();
            var optclass = $(this).prop('class');
            var opttext = $(this).text();
            optionlist = $('#optionstore').text() + "@%" + optvalue + "@%" + optclass + "@%" + opttext;
            $('#optionstore').text(optionlist);
        });
    }

    //Delete everything
    $('option[class^="sub-"]').remove();

    // Put the filtered stuff back
    populateoption = rewriteoption(myfilter);
    $('#foodType').html(populateoption);
}

function rewriteoption(myfilter) {
    //Rewrite only the filtered stuff back into the option
    var options = $('#optionstore').text().split('@%');
    var resultgood = false;
    var myfilterclass = "sub-" + myfilter;
    var optionlisting = "";

    myfilterclass = (myfilter != "")?myfilterclass:"all";

    //First variable is always the value, second is always the class, third is always the text
    for (var i = 3; i < options.length; i = i + 3) {
        if (options[i - 1] == myfilterclass || myfilterclass == "all") {
            optionlisting = optionlisting + '<option value="' + options[i - 2] + '" class="' + options[i - 1] + '">' + options[i] + '</option>';
            resultgood = true;
        }
    }
    if (resultgood) {
        return optionlisting;
    }
}

#6


11  

This works in Firefox 3.0, but not in MSIE 8, nor in Opera 9.62:

这适用于Firefox 3.0,但不是MSIE 8,也不是Opera 9.62:

jQuery('#destinations').children('option[value="1"]').hide();
jQuery('#destinations').children('option[value="1"]').css('display','none');

But rather hiding an option, one can simply disable it:

但是,隐藏一个选项,你可以简单地禁用它:

jQuery('#destinations').val('2'); 
jQuery('#destinations').children('option[value="1"]').attr('disabled','disabled');

The first of the the two lines above is for Firefox and pass focus to the 2nd option (assuming it has value="2"). If we omit it, the option is disabled, but the still displays the "enabled" option before we drop it down. Hence, we pass focus to another option to avoid this.

上面两行中的第一个是Firefox,并将焦点转移到第二个选项(假设它有值="2")。如果我们省略它,选项是禁用的,但是在我们删除它之前,仍然显示“启用”选项。因此,我们将焦点转移到另一个选项来避免这个问题。

#7


4  

Take a look at this question and the answers -

看看这个问题和答案。

Disable select options...

禁用选择选项…

Looking at your code, you may need to quote the attribute value

查看您的代码,您可能需要引用属性值。

$("#edit-field-service-sub-cat-value option[value='title']").hide();

from jQuery attribute selectors

从jQuery属性选择器

Quotes are optional in most cases, but should be used to avoid conflicts when the value contains characters like "]"

在大多数情况下,引号都是可选的,但是当值包含像“]”这样的字符时,应该使用引号来避免冲突。

EDIT:

编辑:

Just realised that you're getting the title from the function parameter, in which case the syntax should be

刚刚意识到您是从函数参数中获取标题的,在这种情况下,语法应该是这样的。

$("#edit-field-service-sub-cat-value option[value='" + title + "']").hide();

#8


4  

In reference to redsquare's suggestion, I ended up doing this:

关于redsquare的建议,我最后做了以下这些:

var selectItems = $("#edit-field-service-sub-cat-value option[value=" + title + "]").detach();

and then to reverse this:

然后反过来:

$("#edit-field-service-sub-cat-value").append(selectItems);

#9


3  

Your best bet is to set disabled=true on the option items you want to disable, then in CSS set

您最好的方法是在您想要禁用的选项项上设置禁用的=true,然后在CSS设置中。

option:disabled {
    display: none;
}

That way even if the browser doesn't support hiding the disabled item, it still can't be selected.. but on browsers that do support it, they will be hidden.

这样,即使浏览器不支持隐藏禁用项,它仍然不能被选中。但在支持它的浏览器上,它们将被隐藏。

#10


3  

The problem is that Internet Explorer does not seem to support the hide and show methods for select options. I wanted to hide all options of my ddlReasonCode select which did not have the currently selected type as the value of the attribute "attType".

问题是Internet Explorer似乎不支持隐藏和显示选择选项的方法。我想隐藏我的ddlrational代码选择的所有选项,它没有当前选择的类型作为属性“attType”的值。

While the lovely Chrome was quite satisfied with:

可爱的Chrome浏览器很满意:

//Hiding all options
            $("#ddlReasonCode").children().hide();
            //Showing only the relevant options
            $("#ddlReasonCode").children("option[atttype=\"" + CurrentType + "\"]").show();

This is what IE required (kids, don't try this at CHROME :-)):

这是IE需要的(孩子们,不要在CHROME上尝试:-)):

//Hiding all options
            $("#ddlReasonCode option").each(function (index, val) {
                if ($(this).is('option') && (!$(this).parent().is('span')) && ($(this).atttype != CurrentType))
                    $(this).wrap('<span>').hide();
            });
            //Showing only the relevant options
            $("#ddlReasonCode option").each(function (index, val) {
                if (this.nodeName.toUpperCase() === 'OPTION') {
                    var span = $(this).parent();
                    var opt = this;
                    if ($(this).parent().is('span') && ((this).atttype == CurrentType)) {
                        $(opt).show();
                        $(span).replaceWith(opt);
                    }
                }
            });

I found that wrapping idea at http://ajax911.com/hide-options-selecbox-jquery/

我在http://ajax911.com/hide-options-selecbox-jquery/上发现了这个包装的想法。

#11


2  

It seems that you also have to update the "selected" attribute. Otherwise the currently selected option may continue to display - although it probably will go away when you actually go to select an option (thats what it did for me): Try doing this:

看起来您还必须更新“selected”属性。否则,当前选择的选项可能会继续显示——尽管当你选择一个选项时它可能会消失(这是它为我做的):试着这样做:

$('#mySelector').children('option').hide();
$('#mySelector').children('option').removeAttr("selected"); //this may be overkill.
$('#mySelector').children('option[value="'+SelVal+'"]').show();  
$('#mySelector').children(':visible').attr('selected','selected'); //assuming that something is still on the list.

#12


2  

I was trying to hide options from one select-list based on the selected option from another select-list. It was working in Firefox3, but not in Internet Explorer 6. I got some ideas here and have a solution now, so I would like to share:

我试着从另一个选择列表中选择一个选择列表来隐藏选项。它在Firefox3中工作,但不是在Internet Explorer 6中。我有一些想法,现在有一个解决方案,所以我想分享:

The JavaScript code

function change_fruit(seldd) {
    var look_for_id=''; var opt_id='';
    $('#obj_id').html("");
    $("#obj_id").append("<option value='0'>-Select Fruit-</option>");
    if(seldd.value=='0') {
        look_for_id='N';
    }
    if(seldd.value=='1'){
        look_for_id='Y';
        opt_id='a';
    }
    if(seldd.value=='2') {
        look_for_id='Y';
        opt_id='b';
    }
    if(seldd.value=='3') {
        look_for_id='Y';
        opt_id='c';
    }

    if(look_for_id=='Y') {
        $("#obj_id_all option[id='"+opt_id+"']").each(function() {
          $("#obj_id").append("<option value='"+$(this).val()+"'>"+$(this).text()+"</option>");
        });
    }
    else {
        $("#obj_id_all option").each(function() {
          $("#obj_id").append("<option value='"+$(this).val()+"'>"+$(this).text()+"</option>");
        });
    }
}

The HTML

<select name="obj_id" id="obj_id">
    <option value="0">-Select Fruit-</option>
    <option value="1" id="a">apple1</option>
    <option value="2" id="a">apple2</option>
    <option value="3" id="a">apple3</option>
    <option value="4" id="b">banana1</option>
    <option value="5" id="b">banana2</option>
    <option value="6" id="b">banana3</option>
    <option value="7" id="c">Clove1</option>
    <option value="8" id="c">Clove2</option>
    <option value="9" id="c">Clove3</option>
</select>

<select name="fruit_type" id="srv_type" onchange="change_fruit(this)">
    <option value="0">All</option>
    <option value="1">Starts with A</option>
    <option value="2">Starts with B</option>
    <option value="3">Starts with C</option>
</select>

<select name="obj_id_all" id="obj_id_all" style="display:none;">
    <option value="1" id="a">apple1</option>
    <option value="2" id="a">apple2</option>
    <option value="3" id="a">apple3</option>
    <option value="4" id="b">banana1</option>
    <option value="5" id="b">banana2</option>
    <option value="6" id="b">banana3</option>
    <option value="7" id="c">Clove1</option>
    <option value="8" id="c">Clove2</option>
    <option value="9" id="c">Clove3</option>
</select>

It was checked as working in Firefox 3 and Internet Explorer 6.

它在Firefox 3和Internet Explorer 6中被选中。

#13


1  

To avoid string concatenation you can use jQuery.grep

为了避免字符串连接,可以使用jQuery.grep。

$($.grep($("#edit-field-service-sub-cat-value option"),
         function(n,i){
           return n.value==title;
         })
 ).hide()

#14


1  

Probably not as elegant or as reusable as a jquery plugin. but another approach is to simply save option elements and swap them out as required:

可能不像jquery插件那样优雅或可重用。但另一种方法是简单地保存选项元素,并按要求将它们进行交换:

var SelectFilter = function ()
        {
            this.allOptions = $("#someSelect option");

            this.fooBarOptions= $("#someSelect option[value='foo']");
            this.fooBarOptions= this.fooBarOptions.add($("#someSelect option[value='bar']"));


            this.showFooBarOptions = function()
            {
                $("#someSelect option").remove();
                $("#someSelect").append(this.fooBarOptions);
            };
            this.showAllOptions = function()
            {
                $("#someSelect option").remove();
                $("#someSelect").append(this.allOptions);
            };



        };

do this to use the object:

使用对象:

var filterObject = new SelectFilter();
filterObject.showFooBarOptions (); 

#15


1  

I implemented a solution using a function that filters a combobox (<select>) based on custom data- attributes. This solution supports:

我使用一个函数实现了一个解决方案,该函数根据自定义数据属性过滤combobox (

  • Having an <option> to show when the filter would leave the select empty.
  • 有一个 <选项> ,以显示过滤器何时将选择空。
  • Respects existing selected attributes.
  • 尊重现有的选择属性。
  • <option> elements without the data-filter attribute are left untouched.
  • <选项> 元素没有数据过滤属性,保持不变。

Tested with jQuery 2.1.4 and Firefox, Chrome, Safari and IE 10+.

使用jQuery 2.1.4和Firefox、Chrome、Safari和ie10 +测试。

This is the example HTML:

这是一个示例HTML:

<select id="myCombobox">
  <option data-filter="1" value="AAA">Option 1</option>
  <option data-filter="1" value="BBB">Option 2</option>
  <option data-filter="2" value="CCC">Option 3</option>
  <option data-filter="2" value="DDD">Option 4</option>
  <option data-filter="3" value="EEE">Option 5</option>
  <option data-filter="3" value="FFF">Option 6</option>
  <option data-filter-emptyvalue disabled>No Options</option>
</select>

The jQuery code for the filtering:

过滤的jQuery代码:

function filterCombobox(selectObject, filterValue, autoSelect) {

  var fullData = selectObject.data("filterdata-values");
  var emptyValue = selectObject.data("filterdata-emptyvalue");

  // Initialize if first time.
  if (!fullData) {
    fullData = selectObject.find("option[data-filter]").detach();
    selectObject.data("filterdata-values", fullData);
    emptyValue = selectObject.find("option[data-filter-emptyvalue]").detach();
    selectObject.data("filterdata-emptyvalue", emptyValue);
    selectObject.addClass("filtered");
  }
  else {
    // Remove elements from DOM
    selectObject.find("option[data-filter]").remove();
    selectObject.find("option[data-filter-emptyvalue]").remove();
  }

  // Get filtered elements.
  var toEnable = fullData.filter("option[data-filter][data-filter='" + filterValue + "']");

  // Attach elements to DOM
  selectObject.append(toEnable);

  // If toEnable is empty, show empty option.
  if (toEnable.length == 0) {
    selectObject.append(emptyValue);
  }

  // Select First Occurrence
  if (autoSelect) {
    var obj = selectObject.find("option[selected]");
    selectObject.val(obj.length == 0 ? toEnable.val() : obj.val());
  }
}

To use it, you just call the function with the value you want to keep.

要使用它,只需用想要保留的值调用函数。

filterCombobox($("#myCombobox"), 2, true);

Then the resulting select will be:

然后产生的选择将是:

<select id="myCombobox">
  <option data-filter="2" value="CCC">Option 3</option>
  <option data-filter="2" value="DDD">Option 4</option>
</select>

The original elements are stored by the data() function, so subsequent calls will add and remove the correct elements.

原始元素存储在data()函数中,因此后续调用将添加和删除正确的元素。

#16


0  

The answer points out that @ is invalid for newer jQuery iterations. While that's correct, some older IEs still dont hide option elements. For anyone having to deal with hiding option elements in those versions affected, I posted a workaround here:

答案指出@对于更新的jQuery迭代是无效的。虽然这是正确的,但有些老年人仍然不隐藏选项。对于那些在那些版本中需要处理隐藏选项元素的人,我在这里发布了一个解决方案:

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

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

Basically just wrap it with a span and replace on show.

基本上就是用一个span把它包起来,然后用show来代替。

#17


0  

Anybody stumbling across this question might also consider the use of Chosen, which greatly expands the capabilities of selects.

遇到这个问题的人也可以考虑选择的使用,这大大扩展了选择的能力。

#18


0  

$("option_you_want_to_hide").addClass('hidden')

Then, in your css make sure you have

然后,在你的css中确保你有。

.hidden{
    display:none;
}

#19


0  

I know this question has been answered. But my requirement was slightly different. Instead of value I wanted to filter by text. So i modified the answer by @William Herry like this.

我知道这个问题已经回答了。但我的要求略有不同。我想用文本来代替值。所以我就像这样修改了@William Herry的答案。

var array = ['Administration', 'Finance', 'HR', 'IT', 'Marketing', 'Materials', 'Reception', 'Support'];
if (somecondition) {
   $(array).each(function () {
       $("div#deprtmnts option:contains(" + this + ")").unwrap();
   });
}
else{
   $(array).each(function () {
       $("div#deprtmnts option:contains(" + this + ")").wrap('<span/>');
   });
}

This way you can use value also by replacing contains like this

这样,您也可以通过替换包含这样的内容来使用值。

 $("div#ovrcateg option[value=" + this + "]").wrap('<span/>');

#20


0  

For hide option in select use:

选择使用的隐藏选项:

option_node.hidden = true; # For hide selcet item
option_node.hidden = false; # For show selcet item

Where option_node is HTMLOptionElement

在option_node HTMLOptionElement

P.S.: I do not use JQuery, but guessing, that it's will works:

注::我不使用JQuery,但猜测它会起作用:

$('.my_select option[value="my_cool_value"]').hidden = true

#21


-1  

$('#id').val($('#id option:eq(0)').hide());

$(" # id”)。瓦尔($(' # id选项:情商(0)')hide());

option:eq(0)-hide option at index '0' in select box.

选项:eq(0)-hide选项在index '0'在选择框。

#1


100  

For what it's worth, the second form (with the @) doesn't exist in jQuery 1.3. The first isn't working because you're apparently expecting variable interpolation. Try this:

对于它的价值,第二个表单(@)不存在于jQuery 1.3中。第一个是无效的,因为显然你期望的是变量插值。试试这个:

$("#edit-field-service-sub-cat-value option[value=" + title + "]").hide();

Note that this will probably break in various hideous ways if title contains jQuery selector metacharacters.

注意,如果标题包含jQuery选择器元字符,那么它可能会以各种可怕的方式中断。

#2


80  

You cannot do this x-browser. If I recall ie has issues. The easiest thing to do is keep a cloned copy of the select before you remove items, this allows you to easily remove and then append the missing items back.

你不能做这个x-浏览器。如果我记得ie有问题。最简单的做法是在删除条目之前保留select的克隆副本,这样可以轻松删除并将丢失的项追加到后面。

#3


47  

Here is my spin, likely a bit faster due to native DOM methods

这是我的自旋,可能是由于本地DOM方法更快一些。

$.each(results['hide'], function(name, title) {                     
    $(document.getElementById('edit-field-service-sub-cat-value').options).each(function(index, option) {
      if( option.value == title ) {
        option.hidden = true; // not fully compatible. option.style.display = 'none'; would be an alternative or $(option).hide();
      }
    });
});

#4


47  

I found a better way, and it is very simple:

我找到了一个更好的方法,而且很简单:

$("option_you_want_to_hide").wrap('<span/>')

To show again, just find that option(not span) and $("option_you_want_to_show").unwrap().

要再次显示,只需找到该选项(不是span)和$("option_you_want_to_show").unwrap()。

It was tested on Chrome and Firefox.

它在Chrome和Firefox上进行了测试。

#5


12  

It CAN be done cross browser; it just takes some custom programming. Please see my fiddle at http://jsfiddle.net/sablefoste/YVMzt/6/. It was tested to work in Chrome, Firefox, Internet Explorer, and Safari.

可以跨浏览器完成;它只需要一些自定义编程。请参阅我的小提琴在http://jsfiddle.net/sablefoste/yvmzt/6/。它在Chrome、Firefox、Internet Explorer和Safari上进行了测试。

In short, I have a hidden field, #optionstore, which stores the array sequentially (since you can't have Associative Arrays in JavaScript). Then when you change the category, it parses the existing options (first time through only) writes them to #optionstore, erases everything, and puts back only the ones associated with the category.

简而言之,我有一个隐藏的字段#optionstore,它按顺序存储数组(因为在JavaScript中不能有关联数组)。然后,当您更改类别时,它会解析现有选项(第一次只通过)将它们写入#optionstore,删除所有内容,并只返回与该类别相关的选项。

NOTE: I created this to allow different option values from the text displayed to the user, so it is highly flexible.

注意:我创建这个是为了让文本显示给用户不同的选项值,所以它非常灵活。

The HTML:

HTML:

<p id="choosetype">
    <div>
        Food Category:
    </div>
    <select name="category" id="category" title="OPTIONAL - Choose a Category to Limit Food Types" size="1">
        <option value="">All Food</option>
        <option value="Food1">Fruit</option>
        <option value="Food2">Veggies</option>
        <option value="Food3">Meat</option>
        <option value="Food4">Dairy</option>
        <option value="Food5">Bread</option>
    </select>
    <div>
        Food Selection
    </div>
    <select name="foodType" id="foodType" size="1">
        <option value="Fruit1" class="sub-Food1">Apples</option>
        <option value="Fruit2" class="sub-Food1">Pears</option>
        <option value="Fruit3" class="sub-Food1">Bananas</option>
        <option value="Fruit4" class="sub-Food1">Oranges</option>
        <option value="Veg1" class="sub-Food2">Peas</option>
        <option value="Veg2" class="sub-Food2">Carrots</option>
        <option value="Veg3" class="sub-Food2">Broccoli</option>
        <option value="Veg4" class="sub-Food2">Lettuce</option>
        <option value="Meat1" class="sub-Food3">Steak</option>
        <option value="Meat2" class="sub-Food3">Chicken</option>
        <option value="Meat3" class="sub-Food3">Salmon</option>
        <option value="Meat4" class="sub-Food3">Shrimp</option>
        <option value="Meat5" class="sub-Food3">Tuna</option>
        <option value="Meat6" class="sub-Food3">Pork</option>
        <option value="Dairy1" class="sub-Food4">Milk</option>
        <option value="Dairy2" class="sub-Food4">Cheese</option>
        <option value="Dairy3" class="sub-Food4">Ice Cream</option>
        <option value="Dairy4" class="sub-Food4">Yogurt</option>
        <option value="Bread1" class="sub-Food5">White Bread</option>
        <option value="Bread2" class="sub-Food5">Panini</option>
    </select>
    <span id="optionstore" style="display:none;"></span>
</p>

The JavaScript/jQuery:

JavaScript / jQuery:

$(document).ready(function() {
    $('#category').on("change", function() {
        var cattype = $(this).val();
        optionswitch(cattype);
    });
});

function optionswitch(myfilter) {
    //Populate the optionstore if the first time through
    if ($('#optionstore').text() == "") {
        $('option[class^="sub-"]').each(function() {
            var optvalue = $(this).val();
            var optclass = $(this).prop('class');
            var opttext = $(this).text();
            optionlist = $('#optionstore').text() + "@%" + optvalue + "@%" + optclass + "@%" + opttext;
            $('#optionstore').text(optionlist);
        });
    }

    //Delete everything
    $('option[class^="sub-"]').remove();

    // Put the filtered stuff back
    populateoption = rewriteoption(myfilter);
    $('#foodType').html(populateoption);
}

function rewriteoption(myfilter) {
    //Rewrite only the filtered stuff back into the option
    var options = $('#optionstore').text().split('@%');
    var resultgood = false;
    var myfilterclass = "sub-" + myfilter;
    var optionlisting = "";

    myfilterclass = (myfilter != "")?myfilterclass:"all";

    //First variable is always the value, second is always the class, third is always the text
    for (var i = 3; i < options.length; i = i + 3) {
        if (options[i - 1] == myfilterclass || myfilterclass == "all") {
            optionlisting = optionlisting + '<option value="' + options[i - 2] + '" class="' + options[i - 1] + '">' + options[i] + '</option>';
            resultgood = true;
        }
    }
    if (resultgood) {
        return optionlisting;
    }
}

#6


11  

This works in Firefox 3.0, but not in MSIE 8, nor in Opera 9.62:

这适用于Firefox 3.0,但不是MSIE 8,也不是Opera 9.62:

jQuery('#destinations').children('option[value="1"]').hide();
jQuery('#destinations').children('option[value="1"]').css('display','none');

But rather hiding an option, one can simply disable it:

但是,隐藏一个选项,你可以简单地禁用它:

jQuery('#destinations').val('2'); 
jQuery('#destinations').children('option[value="1"]').attr('disabled','disabled');

The first of the the two lines above is for Firefox and pass focus to the 2nd option (assuming it has value="2"). If we omit it, the option is disabled, but the still displays the "enabled" option before we drop it down. Hence, we pass focus to another option to avoid this.

上面两行中的第一个是Firefox,并将焦点转移到第二个选项(假设它有值="2")。如果我们省略它,选项是禁用的,但是在我们删除它之前,仍然显示“启用”选项。因此,我们将焦点转移到另一个选项来避免这个问题。

#7


4  

Take a look at this question and the answers -

看看这个问题和答案。

Disable select options...

禁用选择选项…

Looking at your code, you may need to quote the attribute value

查看您的代码,您可能需要引用属性值。

$("#edit-field-service-sub-cat-value option[value='title']").hide();

from jQuery attribute selectors

从jQuery属性选择器

Quotes are optional in most cases, but should be used to avoid conflicts when the value contains characters like "]"

在大多数情况下,引号都是可选的,但是当值包含像“]”这样的字符时,应该使用引号来避免冲突。

EDIT:

编辑:

Just realised that you're getting the title from the function parameter, in which case the syntax should be

刚刚意识到您是从函数参数中获取标题的,在这种情况下,语法应该是这样的。

$("#edit-field-service-sub-cat-value option[value='" + title + "']").hide();

#8


4  

In reference to redsquare's suggestion, I ended up doing this:

关于redsquare的建议,我最后做了以下这些:

var selectItems = $("#edit-field-service-sub-cat-value option[value=" + title + "]").detach();

and then to reverse this:

然后反过来:

$("#edit-field-service-sub-cat-value").append(selectItems);

#9


3  

Your best bet is to set disabled=true on the option items you want to disable, then in CSS set

您最好的方法是在您想要禁用的选项项上设置禁用的=true,然后在CSS设置中。

option:disabled {
    display: none;
}

That way even if the browser doesn't support hiding the disabled item, it still can't be selected.. but on browsers that do support it, they will be hidden.

这样,即使浏览器不支持隐藏禁用项,它仍然不能被选中。但在支持它的浏览器上,它们将被隐藏。

#10


3  

The problem is that Internet Explorer does not seem to support the hide and show methods for select options. I wanted to hide all options of my ddlReasonCode select which did not have the currently selected type as the value of the attribute "attType".

问题是Internet Explorer似乎不支持隐藏和显示选择选项的方法。我想隐藏我的ddlrational代码选择的所有选项,它没有当前选择的类型作为属性“attType”的值。

While the lovely Chrome was quite satisfied with:

可爱的Chrome浏览器很满意:

//Hiding all options
            $("#ddlReasonCode").children().hide();
            //Showing only the relevant options
            $("#ddlReasonCode").children("option[atttype=\"" + CurrentType + "\"]").show();

This is what IE required (kids, don't try this at CHROME :-)):

这是IE需要的(孩子们,不要在CHROME上尝试:-)):

//Hiding all options
            $("#ddlReasonCode option").each(function (index, val) {
                if ($(this).is('option') && (!$(this).parent().is('span')) && ($(this).atttype != CurrentType))
                    $(this).wrap('<span>').hide();
            });
            //Showing only the relevant options
            $("#ddlReasonCode option").each(function (index, val) {
                if (this.nodeName.toUpperCase() === 'OPTION') {
                    var span = $(this).parent();
                    var opt = this;
                    if ($(this).parent().is('span') && ((this).atttype == CurrentType)) {
                        $(opt).show();
                        $(span).replaceWith(opt);
                    }
                }
            });

I found that wrapping idea at http://ajax911.com/hide-options-selecbox-jquery/

我在http://ajax911.com/hide-options-selecbox-jquery/上发现了这个包装的想法。

#11


2  

It seems that you also have to update the "selected" attribute. Otherwise the currently selected option may continue to display - although it probably will go away when you actually go to select an option (thats what it did for me): Try doing this:

看起来您还必须更新“selected”属性。否则,当前选择的选项可能会继续显示——尽管当你选择一个选项时它可能会消失(这是它为我做的):试着这样做:

$('#mySelector').children('option').hide();
$('#mySelector').children('option').removeAttr("selected"); //this may be overkill.
$('#mySelector').children('option[value="'+SelVal+'"]').show();  
$('#mySelector').children(':visible').attr('selected','selected'); //assuming that something is still on the list.

#12


2  

I was trying to hide options from one select-list based on the selected option from another select-list. It was working in Firefox3, but not in Internet Explorer 6. I got some ideas here and have a solution now, so I would like to share:

我试着从另一个选择列表中选择一个选择列表来隐藏选项。它在Firefox3中工作,但不是在Internet Explorer 6中。我有一些想法,现在有一个解决方案,所以我想分享:

The JavaScript code

function change_fruit(seldd) {
    var look_for_id=''; var opt_id='';
    $('#obj_id').html("");
    $("#obj_id").append("<option value='0'>-Select Fruit-</option>");
    if(seldd.value=='0') {
        look_for_id='N';
    }
    if(seldd.value=='1'){
        look_for_id='Y';
        opt_id='a';
    }
    if(seldd.value=='2') {
        look_for_id='Y';
        opt_id='b';
    }
    if(seldd.value=='3') {
        look_for_id='Y';
        opt_id='c';
    }

    if(look_for_id=='Y') {
        $("#obj_id_all option[id='"+opt_id+"']").each(function() {
          $("#obj_id").append("<option value='"+$(this).val()+"'>"+$(this).text()+"</option>");
        });
    }
    else {
        $("#obj_id_all option").each(function() {
          $("#obj_id").append("<option value='"+$(this).val()+"'>"+$(this).text()+"</option>");
        });
    }
}

The HTML

<select name="obj_id" id="obj_id">
    <option value="0">-Select Fruit-</option>
    <option value="1" id="a">apple1</option>
    <option value="2" id="a">apple2</option>
    <option value="3" id="a">apple3</option>
    <option value="4" id="b">banana1</option>
    <option value="5" id="b">banana2</option>
    <option value="6" id="b">banana3</option>
    <option value="7" id="c">Clove1</option>
    <option value="8" id="c">Clove2</option>
    <option value="9" id="c">Clove3</option>
</select>

<select name="fruit_type" id="srv_type" onchange="change_fruit(this)">
    <option value="0">All</option>
    <option value="1">Starts with A</option>
    <option value="2">Starts with B</option>
    <option value="3">Starts with C</option>
</select>

<select name="obj_id_all" id="obj_id_all" style="display:none;">
    <option value="1" id="a">apple1</option>
    <option value="2" id="a">apple2</option>
    <option value="3" id="a">apple3</option>
    <option value="4" id="b">banana1</option>
    <option value="5" id="b">banana2</option>
    <option value="6" id="b">banana3</option>
    <option value="7" id="c">Clove1</option>
    <option value="8" id="c">Clove2</option>
    <option value="9" id="c">Clove3</option>
</select>

It was checked as working in Firefox 3 and Internet Explorer 6.

它在Firefox 3和Internet Explorer 6中被选中。

#13


1  

To avoid string concatenation you can use jQuery.grep

为了避免字符串连接,可以使用jQuery.grep。

$($.grep($("#edit-field-service-sub-cat-value option"),
         function(n,i){
           return n.value==title;
         })
 ).hide()

#14


1  

Probably not as elegant or as reusable as a jquery plugin. but another approach is to simply save option elements and swap them out as required:

可能不像jquery插件那样优雅或可重用。但另一种方法是简单地保存选项元素,并按要求将它们进行交换:

var SelectFilter = function ()
        {
            this.allOptions = $("#someSelect option");

            this.fooBarOptions= $("#someSelect option[value='foo']");
            this.fooBarOptions= this.fooBarOptions.add($("#someSelect option[value='bar']"));


            this.showFooBarOptions = function()
            {
                $("#someSelect option").remove();
                $("#someSelect").append(this.fooBarOptions);
            };
            this.showAllOptions = function()
            {
                $("#someSelect option").remove();
                $("#someSelect").append(this.allOptions);
            };



        };

do this to use the object:

使用对象:

var filterObject = new SelectFilter();
filterObject.showFooBarOptions (); 

#15


1  

I implemented a solution using a function that filters a combobox (<select>) based on custom data- attributes. This solution supports:

我使用一个函数实现了一个解决方案,该函数根据自定义数据属性过滤combobox (

  • Having an <option> to show when the filter would leave the select empty.
  • 有一个 <选项> ,以显示过滤器何时将选择空。
  • Respects existing selected attributes.
  • 尊重现有的选择属性。
  • <option> elements without the data-filter attribute are left untouched.
  • <选项> 元素没有数据过滤属性,保持不变。

Tested with jQuery 2.1.4 and Firefox, Chrome, Safari and IE 10+.

使用jQuery 2.1.4和Firefox、Chrome、Safari和ie10 +测试。

This is the example HTML:

这是一个示例HTML:

<select id="myCombobox">
  <option data-filter="1" value="AAA">Option 1</option>
  <option data-filter="1" value="BBB">Option 2</option>
  <option data-filter="2" value="CCC">Option 3</option>
  <option data-filter="2" value="DDD">Option 4</option>
  <option data-filter="3" value="EEE">Option 5</option>
  <option data-filter="3" value="FFF">Option 6</option>
  <option data-filter-emptyvalue disabled>No Options</option>
</select>

The jQuery code for the filtering:

过滤的jQuery代码:

function filterCombobox(selectObject, filterValue, autoSelect) {

  var fullData = selectObject.data("filterdata-values");
  var emptyValue = selectObject.data("filterdata-emptyvalue");

  // Initialize if first time.
  if (!fullData) {
    fullData = selectObject.find("option[data-filter]").detach();
    selectObject.data("filterdata-values", fullData);
    emptyValue = selectObject.find("option[data-filter-emptyvalue]").detach();
    selectObject.data("filterdata-emptyvalue", emptyValue);
    selectObject.addClass("filtered");
  }
  else {
    // Remove elements from DOM
    selectObject.find("option[data-filter]").remove();
    selectObject.find("option[data-filter-emptyvalue]").remove();
  }

  // Get filtered elements.
  var toEnable = fullData.filter("option[data-filter][data-filter='" + filterValue + "']");

  // Attach elements to DOM
  selectObject.append(toEnable);

  // If toEnable is empty, show empty option.
  if (toEnable.length == 0) {
    selectObject.append(emptyValue);
  }

  // Select First Occurrence
  if (autoSelect) {
    var obj = selectObject.find("option[selected]");
    selectObject.val(obj.length == 0 ? toEnable.val() : obj.val());
  }
}

To use it, you just call the function with the value you want to keep.

要使用它,只需用想要保留的值调用函数。

filterCombobox($("#myCombobox"), 2, true);

Then the resulting select will be:

然后产生的选择将是:

<select id="myCombobox">
  <option data-filter="2" value="CCC">Option 3</option>
  <option data-filter="2" value="DDD">Option 4</option>
</select>

The original elements are stored by the data() function, so subsequent calls will add and remove the correct elements.

原始元素存储在data()函数中,因此后续调用将添加和删除正确的元素。

#16


0  

The answer points out that @ is invalid for newer jQuery iterations. While that's correct, some older IEs still dont hide option elements. For anyone having to deal with hiding option elements in those versions affected, I posted a workaround here:

答案指出@对于更新的jQuery迭代是无效的。虽然这是正确的,但有些老年人仍然不隐藏选项。对于那些在那些版本中需要处理隐藏选项元素的人,我在这里发布了一个解决方案:

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

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

Basically just wrap it with a span and replace on show.

基本上就是用一个span把它包起来,然后用show来代替。

#17


0  

Anybody stumbling across this question might also consider the use of Chosen, which greatly expands the capabilities of selects.

遇到这个问题的人也可以考虑选择的使用,这大大扩展了选择的能力。

#18


0  

$("option_you_want_to_hide").addClass('hidden')

Then, in your css make sure you have

然后,在你的css中确保你有。

.hidden{
    display:none;
}

#19


0  

I know this question has been answered. But my requirement was slightly different. Instead of value I wanted to filter by text. So i modified the answer by @William Herry like this.

我知道这个问题已经回答了。但我的要求略有不同。我想用文本来代替值。所以我就像这样修改了@William Herry的答案。

var array = ['Administration', 'Finance', 'HR', 'IT', 'Marketing', 'Materials', 'Reception', 'Support'];
if (somecondition) {
   $(array).each(function () {
       $("div#deprtmnts option:contains(" + this + ")").unwrap();
   });
}
else{
   $(array).each(function () {
       $("div#deprtmnts option:contains(" + this + ")").wrap('<span/>');
   });
}

This way you can use value also by replacing contains like this

这样,您也可以通过替换包含这样的内容来使用值。

 $("div#ovrcateg option[value=" + this + "]").wrap('<span/>');

#20


0  

For hide option in select use:

选择使用的隐藏选项:

option_node.hidden = true; # For hide selcet item
option_node.hidden = false; # For show selcet item

Where option_node is HTMLOptionElement

在option_node HTMLOptionElement

P.S.: I do not use JQuery, but guessing, that it's will works:

注::我不使用JQuery,但猜测它会起作用:

$('.my_select option[value="my_cool_value"]').hidden = true

#21


-1  

$('#id').val($('#id option:eq(0)').hide());

$(" # id”)。瓦尔($(' # id选项:情商(0)')hide());

option:eq(0)-hide option at index '0' in select box.

选项:eq(0)-hide选项在index '0'在选择框。