Question

I have some trouble with an "option select tree" code. First step it works correctly, but second one nope. I don't understand why...

function show_opt(id,options){
  var n = id.val();
  var nexts = (id.next('select'));

  var showOptions = options.filter('.'+n);
  nexts.html(showOptions);
  nexts.prop('selectedIndex', 0);
}

$(document).ready(function() {
  var select = $('#group1').children('select');
      var sn = select.eq(0);

      sn.change(function(){
        $('#print').val((sn.val()));

        var next_s = sn.next('select');

        var fontOptions = next_s.children('option').remove();
        show_opt(sn,fontOptions);
      });
});

Here is a demo: Jsfiddle

Was it helpful?

Solution

Tip: use debugger to see what are the values of variables that you use.

Basically, your code does the following (assuming you choose, e.g., main_4 from first menu):

  1. on $('#main').change() you remove all 12 <option> elements from #sub0.

  2. you pass those elements (still 12) to show_opt and filter them, so only 3 remain (sub0_4.1 etc.).

  3. you append those 3 elements to #sub0. Now #sub0 has only 3 <option> elements.

  4. on next change() there are only 3 elements in #sub0. Assume you choose main_3 this time - after you filter() those 3 <option> elems in show_opt, none remain.

Hope now it's clear to you why your code doesn't work.

OTHER TIPS

When you filter down the elements the ones you don't need are removed. When you do the second filtering it won't start from the whole set but just from the first filter result

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top