简体   繁体   English

使用jQuery将过滤器应用于选择框

[英]applying a filter to a select box using jQuery

I have a webpage which has two <select> boxes: Hadoop Distribution and Hadoop Version . 我有一个网页,其中有两个<select>框: Hadoop DistributionHadoop Version I also have a map between the Distribution and the Version : 我在Distribution VersionVersion之间也有一张地图:

function hadoop_map() {
      var hash = Object();
      // replace this part of the code by a jQuery post 
      hash['Cloudera'] = ['4', '5'];
      hash['Apache'] = ['2.4', '2.3.0', '2.2.0', '2.1.1', '2.1.0', '2.0.6', '1.2.1'];
      hash['Hortonworks'] = ['2.1', '2.0', '1.3'];
      hash['Pivotal'] = [];
      hash['MapR'] = [];

      return hash;
   }

so, one select is: 因此,一个选择是:

<select id="hadoop_dist">
    <option>Cloudera</option>
    <option>Hortonworks</option>
    <option>Apache</option>
    <option>MapR</option
    <option>Pivotal</option>
</select>

while the other is 而另一个是

<select id="hadoop_version">
   <option>4</option>
   <option>5</option>
   <option>2.3.0</option>
    ...
 </select>

So, when I select Cloudera in the top box, I would like to only display the entries listed in the hadoop_map (ie 4 and 5 ) in the hadoop_version ? 所以,当我选择Cloudera的机顶盒,我想只显示在列出的条目hadoop_map (即45 )在hadoop_version How can I accomplish that using jQuery ? 如何使用jQuery完成此操作?

Because of the nature of your data, one way convenient way is to construct it every time it changes. 由于数据的性质,一种便捷的方法是在每次更改时对其进行构造。 A little inefficient but a lot more readable and easily extendible than alternative options: 与替代选项相比,效率低下但可读性强,易于扩展:

var hadoopMap = hadoop_map();

$('#hadoop_dist').change(function() {
    var selectedOption = $(this).val();
    var $options = $.map(hadoopMap[selectedOption], function(value) {
        return $('<option>').html(value);
    });

    $('#hadoop_version').empty().append($options);
});

By using 通过使用

.find('option').remove() 

and then looping through the array for the chosen has property and using 然后遍历数组的选定has属性并使用

.append('<option>' + item + '</option').

See this jsfiddle for a working example 有关工作示例,请参见此jsfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM