0

I have a ul list which will be created dynamically with increasing number. I have a for loop to bind the click even to all those UL.

What i need to do is when user click on it, remove the previously selected list and add the clicked as selected.

Somehow the k value in the for loop is not correct for the selection of the increasing list, But it is correct for the click function.

I want to know why it(k) is not correct? As it is correctly binded for the click event for all 5 ul but not inside the click event.

When i console.log the k value it prints 6 for all ul. I want to know the reason. How to solve this?

CODE

jQuery(document).ready(function(){
    for(var k=1;k<=5;k++){
        jQuery("#sample"+k+" li").click(function(){
            console.log(k);
            jQuery("#sample"+k+" li.selected").removeAttr('class');//removing previous selection
            jQuery(this).addClass('selected');//adding selection for clicked one
        });
    }
});

JSFIDDLE

rram
  • 2,004
  • 5
  • 24
  • 37

2 Answers2

1

You can use jQuery event delegation to listen to an event on the parent and pass it to the child. This is the preferred method for capturing dynamically-added elements.

See: jQuery event delegation with .on (this reference)

Community
  • 1
  • 1
Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
0

You are trying to bind the value of k in a for loop, but problem is when you are clicking the li the for loop has been finished.

You can bind each value of k with a function.

Do something like bellow

function addClick(k){
    jQuery("#sample"+k+" li").click(function(){
            console.log(k);
            jQuery("#sample"+k+" li.selected").removeAttr('class');//removing previous selection
            jQuery(this).addClass('selected');//adding selection for clicked one
        });
}

jQuery(document).ready(function(){
    for(var k=1;k<=5;k++){
        addClick(k)
    }
});

DEMO

Mritunjay
  • 25,338
  • 7
  • 55
  • 68