jQuery和css:使用某个css类隐藏/显示选择选项

在html代码中我选择了这样的选项:

Value1 

在jQuery中:

 var cod = $(this).val(); // This is the value of another select: when the value $("option[class^=myclass]").hide(); $("option[class^=myclass]").each(function () { $("option[class^=myclass" + cod + "]").show(); }); 

编辑

我有两个选择。 当我在第一个选择中选择一个值时,必须相应地填充第二个值(我必须阻止ajax调用)。

我将所有第二个选择值放在会话var中,但我的问题是只选择那些与第一个选择相关的值,所以我试图通过css类。

EDIT2

  Choose... Value1 Value2 Value3   Choose... Value11 Value12 Value13 Value21 Value22 Value23 Value31 Value32 Value33  

EDIT3

对我来说,绿色的解决方案是好的,但IE上有一个问题,我没有成功解释:当我使用后退按钮时,用户选择的值是“丢失”,也就是说,如果我登录控制台的用户选中的值,我在新的克隆选择中看到它的“索引”。 在html源代码中,有整个原始选择。

EDIT4

我解决了这篇文章

https://forum.jquery.com/topic/jquery-select-box-selectedindex-problems-in-internet-explorer-ie-on-refresh-and-back-buttons

因此,当我正确理解您的问题时,您希望在第一个选择字段中使第二个选择字段的选项取决于所选值。

我快速尝试了这个并且隐藏css的选项似乎不能跨浏览器工作,即使最新版本的chrome on mac也不会隐藏选项。

所以我想出了以下内容:

HTML优先:我使用类来标记依赖项。 这允许在没有限制的情况下使用第二个选择字段中的value属性。

此外,只有标记为conditional选项才会更改,其他选项不会受到影响。 这对于此方案中的“默认”值非常有用。

   

和Javascript:为了使这项工作,我复制了secondSelect字段的选项并将它们保存在一个变量中。 这允许我实际从选择字段中remove选项,而我仍然能够从副本中检索选项。

 $(function(){ var conditionalSelect = $("#secondSelect"), // Save possible options options = conditionalSelect.children(".conditional").clone(); $("#firstSelect").change(function(){ var value = $(this).val(); // Remove all "conditional" options conditionalSelect.children(".conditional").remove(); // Attach options that needs to be displayed for the selected value. options.clone().filter("."+value).appendTo(conditionalSelect); }).trigger("change"); }); 

这里有一个小提琴,显示脚本在行动: http : //jsfiddle.net/Kn8Gc/

注意:如果从数据库中获取数据并且用户已选择#firstSelect,则只需使用selected="selected"属性。 #secondSelect将自动显示正确的值。 只需尝试上面的小提琴并“预选”例如value1而不是0!


这里也是一个“通用”函数,可以很容易地使用任何两个选择字段依赖于彼此(仍然使用类conditional + source value来建立关系):

 // "Generic" function $.conditionalize = function(sourceSelect, conditionalSelect){ var options = conditionalSelect.children(".conditional").clone(); sourceSelect.change(function(){ var value = $(this).val(); conditionalSelect.children(".conditional").remove(); options.clone().filter("."+value).appendTo(conditionalSelect); }).trigger("change"); } // Used like this: $.conditionalize($("#firstSelect"), $("#secondSelect")); 

在这里它是行动: http : //jsfiddle.net/NUxQ9/

在所有浏览器中都未定义隐藏选项。 它没有在W3C规范中定义。

http://www.w3.org/TR/html401/interact/forms.html#h-17.6

根据第一个选择值禁用该选项

您可以禁用第二个选项,该选项不允许用户选择该选项。

演示: http //jsfiddle.net/HrpF2/

码:

 $(function () { var $secondOptions = $('select[name=secondselect] option'); $("select[name=firstselect]").change(function () { var value = $(this).val(); $secondOptions.prop('disabled', true).filter(function () { return this.value == 'myclass' + value; }).prop('disabled', false); }).trigger("change"); }); 

根据第一个选择值显示/隐藏选项

如果您确实要显示/隐藏选项,则需要克隆第二个选项并根据第一个选择值将其添加回来。 见下文,

演示: http //jsfiddle.net/HrpF2/1/

码:

 $(function () { var $secondOptions = $('select[name=secondselect]'); var $cloneOptions = $secondOptions.find('option').clone(); $("select[name=firstselect]").change(function () { var value = $(this).val(); $secondOptions.empty().append($cloneOptions.filter(function () { return this.value == 'myclass' + value; })); }).trigger("change"); }); 

包含具有选择映射的javascript对象

这种类型的问题经常出现在SPA开发中,我开发了这种方法。 我建议使用不同的选项列表创建一个javascript对象,对象键包含将导致兄弟的选择字段的名称:在动态创建选择字段之后,通过绑定到依赖选择的’select’事件元素,并运行自定义脚本来评估所选选项,解析您的地图,然后相应地渲染选项。

我已经采用了这个概念,并创建了一个非常漂亮的shell,不仅应该允许你在你提到的两个选择元素之间进行此操作,而且基本上允许你拥有任意数量的依赖选择元素…填充所有它们基于依赖元素中的选择。 以下是更酷的优势:

  • html标记非常干净
  • 您甚至可以在动态创建的dependee选项上初始化依赖项
  • javascript代码非常干净和精确
  • 这可以很容易地模块化,因此它可以转换成只有几行代码的插件或模块
  • 使用$.extend()和提供的SelectOption对象,可以轻松异步创建新选项并异步更改依赖SelectOption
  • 代码的构建方式可以通过调用自定义函数将不同的选项列表注入到map对象中
  • 将适用于任何可以触发select事件的元素 。 允许您使用非表单元素并注入下拉类型function并仍然影响其他元素(**适用于Bootstrap!

我已经创建了一个要点来展示这些概念。 我在这里列出了初始shell,但请检查链接以确保您拥有关于此要点的最新版本和信息。 (我可以把它变成一个插件)

https://gist.github.com/LongLiveCHIEF/7880119.js

form.html

           

选择-map.js

 // first we map our dependencies var map = { secondselect: [ //high level keys are the fields that will cause cascades 'set1' : {[new SelectOption('','','')],[new SelectOption('','','')],[new SelectOption('','','')]} // this is an option list, with gets a name as a key 'set2' : {[new SelectOption('','','')],[new SelectOption('','','')],[new SelectOption('','','')]}, 'set3' : {[new SelectOption('','','')],[new SelectOption('','','')],[new SelectOption('','','')]}, ], fourthselect: [ 'set1' : {[new SelectOption('','','')],[new SelectOption('','','')],[new SelectOption('','','')]} ] }; // now we make it easy to inject select options at any point var SelectOption = function(text, value, dependenSelectFields){ return {}; //retun object with properties corresponding to the attributes and values of a specific option } //and now we kick off processing var $primaryElements = $.data('selmap-cascade'); // create a collection consisting of any and all elements with selmap-cascade data option //here we act when any designated dependent field has a selection change $primaryelements.select(function(){ var mapkey = $(this + ':selected').data('selmap-set-cascade'); // get the data that will allow us to grab the proper select options for the dependent elements //and now we render the correct option into the correct place in the DOM }); 

我让它跨浏览器工作的唯一方法是分离然后重新附加选项。 我为每个选项添加了一个类,以便除了分组之外还打破选项的值。 这两件事可能有关系,但我不会这么认为。

   

和Javascript ……

 var groups = false; function update_selected() { // reset the secondselect $("#secondselect").val(0); $("#secondselect").find("option[value!=0]").detach(); // re-attach the correct options $("#secondselect").append(groups.filter(".group" + $(this).val())); } $(function() { // initialize by detaching all the options (except for the "Choose..." option) groups = $("#secondselect").find("option[value!=0]"); groups.detach(); // add the onchange event handler $("#firstselect").change(update_selected); // immediately call update_selected to update on page load $("#firstselect").trigger("change"); }); 

小提琴: http : //jsfiddle.net/JbVWV/8/

编辑 – 我在页面加载时添加了对$("#firstselected").trigger("change")的调用。 因此,如果第一个下拉列表中已选择了某些内容,则第二个下拉列表将已正确填充。

我不确定我完全理解你的问题,但是这样的事情怎么样:

 $(document).ready(function(){ var cod = ''; $('select[name="firstselect"]').change(function(){ cod = $(this).val(); if ( cod > 0 ) { $('select[name="secondselect"] option').hide().filter(function(){ return ( $(this).val().substr(7,1) == cod || $(this).val() == 0 ); }).show(); } }); }); 

http://jsfiddle.net/wVCcH/1/

或者 ,动态写入选项也存在:

 var dataset = [ { set: 1, data: [ { val: "value11", label: "Value 1 - 1" }, { val: "value12", label: "Value 1 - 2" }, { val: "value13", label: "Value 1 - 3" } ] }, { set: 2, data: [ { val: "value21", label: "Value 2 - 1" }, { val: "value22", label: "Value 2 - 2" }, { val: "value23", label: "Value 2 - 3" } ] }]; var chooser = ""; $('select[name="firstselect"]').change(function(){ var n = $(this).val(); //get value of data set if ( n != 0 ) { var str = chooser; n--; //0-based n for (i=0; i" + dataset[n].data[i].label + "" } $('select[name="secondselect"]').html(str).attr("disabled",false); } }); 

http://jsfiddle.net/UNy9Z/4/