0

I'm a bit stumped as to why this code is failing and have used numerous examples, but with no success.

This JS Fiddle is the exact issue I'm stuck on. You will notice that you can create a new row by clicking on the '+' icon, but when you attempt to remove a row by clicking on the trash can icon, presently, it should popup an alert just affirming that we made it into the function. This never happens and henceforth, is the reason for this post.

$("[id^=removeitem]").click(function() {
  var elmId = $(this).attr('id');
  alert(elmId);
});

Any help would be so very appreciated!

Skittles
  • 2,866
  • 9
  • 31
  • 37
  • Your selector is not incorrect. Your manner of binding is. – Taplar May 20 '19 at 18:09
  • @Taplar - Can you please elaborate? I'm clearly missing something. The id values are unique as they are assigned a number at the end of the static name. Thus defining a unique name. id="removeitem' + hiCount + '" So, what am I missing or, as you stated, "Your manner of binding is.". – Skittles May 20 '19 at 18:16
  • @Taplar - Due to your comment about binding, I just tried this and it still isn't working; $( "[id^=removeitem] ).on( "click", function() { console.log('Works'); }); – Skittles May 20 '19 at 18:31
  • 1
    Ahhhh, I missed the number on the end of the id. In any case, this logic should really use a common class with contextual lookups. – Taplar May 20 '19 at 18:31
  • 1
    you need to check the duplicate I linked. The issue is that the elements are created dynamically. – Taplar May 20 '19 at 18:32
  • I did check that link. I guess it doesn't make sense to me though as once the element is rendered, even through dynamic creation, doesn't it still take on all the same functional properties of statically defined page content? – Skittles May 20 '19 at 18:34
  • 1
    http://learn.jquery.com/events/event-delegation/ You cannot bind on an element before it exists. – Taplar May 20 '19 at 18:35
  • OUCH!!! Well talk about throwing a massive monkey wrench into the gears. O.o – Skittles May 20 '19 at 18:36
  • 1
    Not a massive issue. Just read that link, or the learn.jquery.com link, to learn about delegate event bindings. – Taplar May 20 '19 at 18:36
  • Okay...I'll see what options that provides. Thanks, Taplar. – Skittles May 20 '19 at 18:37
  • @Taplar - That most certainly was the issue and your help is immensely appreciated! Additionally I will be changing the selector over to a class as your also recommended. Thank you very much! – Skittles May 20 '19 at 18:45
  • @Taplar - If you would like to provide an answer, I will most gladly accept it as the accepted solution. If not, I'll just answer it myself with credit being given to you for the assist. – Skittles May 20 '19 at 18:47
  • 1
    It's already a duplicate post, due to the other question. It should be closed as such. – Taplar May 20 '19 at 18:53

0 Answers0