filter类别根据另一个下拉选项选择下拉列表

我想根据另一个下拉列表的选择过滤选项列表。

请参阅下面的jquery代码; 我确信有一点点我错过了,这就是为什么它不起作用。

if($('#selectionone').is(':selected')){ $('option').filter('.edibles'); } if($('selectiontwo').is(':selected')){ $('option').filter('.vegfats'); } 

这是jsfiddle链接

这是我根据所选选项添加/删除选项的方法,这将适用于大多数浏览器。

我已经通过将类添加到第一个选择选项来修改html

   

JS:

 $(document).ready(function () { var allOptions = $('#selectprod option') $('#selectcat').change(function () { $('#selectprod option').remove(); //remove all options var classN = $('#selectcat option:selected').prop('class'); //get the var opts = allOptions.filter('.' + classN); //selected option's classname $.each(opts, function (i, j) { $(j).appendTo('#selectprod'); //append those options back }); }); }); 

的jsfiddle

你可以这样做:

 $(document).ready(function () { $('#selectcat').change(function () { $('#selectprod option').show(); if ($('option:selected', this).attr('id') == 'selectionone') { $('#selectprod option.edibles').hide(); } if ($('option:selected', this).attr('id') == 'selectiontwo') { $('#selectprod option.vegfats').hide(); } }); }); 

jsFiddle示例

由于这可能不适用于旧版本的IE,您可以替换$('#selectprod option').show(); with $('#selectprod option').prop('disabled',false);$('#selectprod option.vegfats').hide(); with $('#selectprod option.vegfats').prop('disabled',true);

这是解决问题的简单方法,应该是相当可靠的:

  

CSS:

 .hiddenOptions > select { display: none; } .hiddenOptions > select.active { display: inline-block; } 

JS:

 $('.masterSelect').on('change', function() { $('.hiddenOptions select').removeClass("active"); $('.hiddenOptions select').eq($(this).val()).addClass("active"); showValue(); }); $('.hiddenOptions select').on('change', function() { showValue(); }); $('.masterSelect').trigger('change'); //set initial value on load function showValue() { console.log($('.hiddenOptions select.active').val()); } 

https://jsfiddle.net/g5h2k6t4/1/

包括这两个链接以及Praveen给出的代码