简体   繁体   中英

applying a filter to a select box using jQuery

I have a webpage which has two <select> boxes: Hadoop Distribution and Hadoop Version . I also have a map between the Distribution and the Version :

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 ? How can I accomplish that using 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

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

See this jsfiddle for a working example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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