naneri
naneri

Reputation: 3971

Jquery multiple selects trigger change

I have a category tree and I am using Jquery on my page to generate a new category select after a previous category has been chosen.

What I need is, if I pass a list of categories (which are ancestors and children of each other), use the code to perform the value selection (which will call the method that I have written previously).

Here is the code that is responsible to fire upon the category change:

$(document.body).on('change', '.category-select' ,function(event){

  var select_rank = parseInt($(event.target).attr('rank'));

  var current_category = event.target.value;

  select_category(select_rank, current_category, true)
});

When page is rendered there is code that will create the first select. Then on each select change - the select_category function will render a new select (if the category has subcategories).

I am passing a list of categories in an array called cat_list. If it is set, I need the selects to be triggered on last select:

if(cat_list != null){
    for(cat_id in cat_list){
        $('.category-select').last().val(cat_id).change();
    }
}

Upvotes: 0

Views: 800

Answers (1)

Barmar
Barmar

Reputation: 780974

You're not iterating over the array correctly. In your code, cat_id is the array index, not the value from the array. Try this:

if (cat_list) {
    var last_select = $('.category-select:last');
    $.each(cat_list, function(i, cat_id) {
        last_select.val(cat_id).change();
    });
}

Upvotes: 2

Related Questions