nabila_ahmed
nabila_ahmed

Reputation: 71

onclick doesn't work properly after append

In my code I am creating unordered list items on the fly. Each of which contains a text and an anchor tag (red cross sign). Now what I want is that on clicking the anchor tag it prints the child number of the list item it's in. I want this without reloading the page.

 if (status === 'success') {
     const i = document.createElement("i");
     i.classList.add("fa");
     i.classList.add("fa-times");
     i.classList.add('red-cross');

     const a = document.createElement("a");
     a.classList.add("ml-4");
     a.append(i);

     const t = document.createTextNode(txt)

     const newItem = document.createElement("li");
     newItem.append(t);
     newItem.append(a);

     $("ul#"+list).append(newItem).on('click', 'li a', function() {
         const cnt =  $("ul#"+list).children().length;
         console.log(cnt);
     }); }

View: Unordered list of items with text and cross sign

Expected output: On clicking i'th cross sign, the output should be i.

Current output: The output is always 6 regardless which number cross I click.

Upvotes: 1

Views: 76

Answers (2)

user1320635
user1320635

Reputation:

The click function is not run until you have clicked on the link. So the const cnt = $("ul#"+list).children().length; will not be calculated until you click, and I guess all your items has been added at that point hence the result of 6 for all of them.

To use that method you have to invoke the calculation when the function is created as this:

$("ul#"+list).append(newItem).on('click', 'li a', (function() {
    const cnt =  $("ul#"+list).children().length;

    return function () {
        console.log(cnt);
    }
}()));

This is not a good solution however since you add a new event listener for each item added. You are probably better of with something like:

var list = $("ul#test");
list.on('click', 'li a', function () {
    var idx = list.children().index($(this).closest('li'));
  console.log(idx);
});

That has to be done only once, then add the new items with just:

$("ul#test").append(newItem);

Upvotes: 1

E. Sundin
E. Sundin

Reputation: 4181

Expected output: On clicking i'th cross sign output shoud be i.

Current output: The output is always 6 regardless which number cross I click.

If clicking i-th li should output i (the index of the li) of n (the total number of li) then you should do something like

const children =  $("ul#"+list + " li a").children();
const i = children.index(this) + 1 // +1 to count from 1
console.log(i);

This checks at which position the clicked a is at - and since you only have one <i> for each <a> the count is the same.

Upvotes: 0

Related Questions