0

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();
    }
}
14
  • can you show us some code and what you are try Commented Dec 24, 2015 at 16:25
  • There are also many past questions about creating selects that depend on a previous select. Do some searching. Commented Dec 24, 2015 at 16:25
  • @MBehtemam I have added the code Commented Dec 24, 2015 at 16:31
  • @Barmar I added some clarifications Commented Dec 24, 2015 at 16:32
  • 1
    Don't use for-in to iterate over arrays. Commented Dec 24, 2015 at 16:35

1 Answer 1

2

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();
    });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.