0

Please take a look at this jsFiddle. Based on a click, an appended class is added to div. I'm trying to click based on the class and get a response. Your help is greatly appreciate!

jQuery(document).ready(function () {

    var count = 0;
    $("#more_time").click(function () {
        count += 1;

        $("#list_times").append($("#more_time").text() + " - <span id='remove_" + count + "' class='remove' style='cursor:pointer; '>(remove)</span><br>");
    });

    $(".remove").on("click", function () {
        alert("Hello");
    });

});

html

<div id="more_time">Weekdays 7:00am - 9:00am - More Time</div>
<br>
<br>
<div id="list_times"></div>
1
  • 1
    Please post your code here, not just in a fiddle.
    – Barmar
    Commented Jun 21, 2013 at 5:19

2 Answers 2

2

Looks like event delegation is your friend here.

Instead of binding the event to the class

$('.remove').on('click', function {  // some code});

Delegate the event to its static parent

$('#list_times').on('click', '.remove', function {  // some code});

Working Fiddle

3
  • +1 for there being an explanation Commented Jun 21, 2013 at 5:26
  • That's awesome! New issue...now the additions I need to remove found here: jsfiddle.net/J8KDv/9 Commented Jun 21, 2013 at 5:50
  • Encase your span in a container.. And then try using closest to target the div container.. Something like this jsfiddle.net/J8KDv/10 Commented Jun 21, 2013 at 5:53
0

Change your .remove binding code to the delegated syntax

$("#list_times").on("click", '.remove', function () {
    alert("Hello");
});

Demo at http://jsfiddle.net/gaby/J8KDv/6/

Not the answer you're looking for? Browse other questions tagged or ask your own question.