-2

I have a click listener set to listen to p a but it's only works once and then no more. I know it's not the code that's running from the click that's the problem because if I run it from the console it runs fine, it's the actual listener that doesn't work.

Listener:

$('p a').click(function() {
    var v = $('p a').prev('input').val();
    $('p a').parent('p').after('<p><input type="text"> <a href="#">Add More</a></p>');
    $('p a').first().parent('p').html('<input type="text" value="' + v + '">');
});

DEMO

Could someone please explain to me why this only runs once?

Spedwards
  • 4,167
  • 16
  • 49
  • 106

2 Answers2

1

Since your new paragraphs and anchors have been added dynamically to the DOM after click handler of first anchor, all the events will not be available to these elements, so in this case you'll need to apply event delegation technique in order to attach those events to these newly added elements:

$(document.body).on('click','p a',function() {
    var v = $('p a').prev('input').val();
    $('p a').parent('p').after('<p><input type="text"> <a href="#">Add More</a></p>');
    $('p a').first().parent('p').html('<input type="text" value="' + v + '">');
});

Updated Fiddle

Felix
  • 37,892
  • 8
  • 43
  • 55
1

The problem is that your event handler removes the existing element that it's attached to and creates a new similar one. Put your handler in a named function, and reattach it to the newly created element, and everything will work fine.

function clickHandler() {
    var v = $('p a').prev('input').val();
    $('p a').parent('p').after('<p><input type="text"> <a href="#">Add More</a></p>');
    $('p a').first().parent('p').html('<input type="text" value="' + v + '">');
    $('p a').click (clickHandler);
}
$('p a').click(clickHandler);
Jules
  • 14,841
  • 9
  • 83
  • 130