2

I'm trying to bind click event in for loop but any of the remove buttons remove only the last list item. Do you have any ideas why this happens?

for ( var key in editedPredef.predefinition) {
      var listItem = $("<li></li>").addClass("ui-widget-content");
      listItem.text("some text");
      var removeListItem = $("<span class=\"ui-icon ui-icon-closethick\"></span>");
      removeListItem.click(function() {
        listItem.remove();
      });
      listItem.append(removeListItem);
      containerElement.append(listItem);
    }
3

2 Answers 2

5

Don't write that inside a for loop just make use of event-delegation,

$(document).on('click','.ui-icon.ui-icon-closethick',function(){
  $(this).closest('li').remove();
});

And note that place this code outside of that for loop.

Sign up to request clarification or add additional context in comments.

5 Comments

@AmitJoki Yeah my PM and TL went outside the office.. :)
PM and TL? Who are they?
Project Manager and Team Leader ;)
@AmitJoki: you are too young to know this bro ;)
@MilindAnantwar, yeah.. maybe
1

Change

removeListItem.click(function() {
    listItem.remove();
  });

to

removeListItem.click(function() {
    $(this).parent('li').remove();
  });

Side Note: this will bind an event handler to each element. You can make use of event delegation like Rajaprabhu mentioned in his answer. However, delegated event handlers will be slower than directly binder event handlers. So it's a matter of how many such elements you are likely to have in your application. If you're going for delegation, it'll be better to bind the event handler to an immediate parent element, which is not dynamically added, so that the response will be faster. For e.g., you can bind the event handler to the parent <ul> if it's not dynamically added and won't be removed from page like

$('ul').on('click','.ui-icon.ui-icon-closethick',function(){
 $(this).parent('li').remove();
});

2 Comments

Harsh downvote. It wasn't me, although for the sake of someone leaving feedback it seems like it was because this could create X anonymous functions. One for each button. Event delegation would mean only creating and calling a single function
@RGraham right, didn't think of that, this is the first thing that came to my mind when i looked at the code… :) i'll mention delegation anyway.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.