简体   繁体   中英

How to I modify the code to apply it for three drop-downs? (Jquery)

I have a jquery code which changes according to the previously selected value of drop-down. I use it when I have two drop-downs and it works flawlessly.

Now the problem is that I am working with 3 drop-downs and I am unable to modify the code according to 3 drop-downs (reason my being new to jquery).

This is the code:

Jquery:

jQuery(function(){
var $cat = $('select[name=coursename]'),
    $items = $('select[name=semno]');

    $cat.change(function(){
    var $this = $(this).find(':selected'),
        rel = $this.attr('rel'),
        $set = $items.find('option.' + rel);

    if ($set.size() < 0) {
        $items.hide();
        return;
    }

    $items.show().find('option').hide();

    $set.show().first().prop('selected', true);});});

I used two drop-downs namely, coursename and semno , with this code and it works perfectly fine.

Now I want to add another dropdown, subnm which comes after semno . So what I exactly want is that when a person makes a particular selection in coursename the relevant items should appear in semno and among those relevant items, when a value is selected, the items are listed on subnm accordingly.

I have used rel and class in the option element.

HTML Code

Course: 
<select name="coursename" id="coursename">
<option value="xyz" rel="xyz">XYZ</option>
<option value="abc" rel="abc">ABC</option>
</select>

Semester: 
<select name="semno" id="sem">
<option value="one" class="xyz">I</option>
<option value="two" class="xyz">II</option>
<option value="three" class="abc">III</option>
</select>

Subject: 
<select name="subnm" id="subnm">
<option value="p">p</option>
<option value="q">q</option>
<option value="r">r</option>
</select>

I guess I will need a rel option on the semno drop-down and then class on the subnm drop-down in accordance to the semno rel.

Forgive me if I am not 100% comprehensible. I am new to this site and I really need help.

Thank You in advance!

Hope this is what you want. I have used the same function for change event for the second select menu.

$items.change(function(){
  var $this = $(this).find(':selected'),
  rel = $this.attr('rel'),
  $set = $third.find('option.' + rel);

  if ($set.size() < 0) {
     $third.hide();
     return;
  }
  $third.show().find('option').hide();
  $set.show().first().prop('selected', true);
});

Also I have triggered the change event for second select in change event handler of first select .

$items.trigger("change");

Please refer this fiddle

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