0

I know this has been asked before but I can't seem to figure out what I'm doing wrong.

I am just trying to create some dynamic elements and then attach an event to them using only JQuery. The buttons should launch an alert.

http://jsfiddle.net/XGb7w/1/

$(function(){   

    $('#add').on("click",function(){addItem()});


    function addItem() {
        var listItem = '<li>' +  '<button class="checkBtn"></button>' + '<button class="crossBtn"></button>' + '</li>';
        $('ul').append(listItem);
    }


    $('.crossBtn').on("click", function() {
        alert() // Doesn't alert why not?
    });



    $('.checkBtn').on("click", function() {
        alert();// Doesn't alert why not?
    })

});

Thank you.

3
  • 1
    Here you go jsfiddle.net/XGb7w/2 Commented Jul 28, 2014 at 19:32
  • You had 3 ;s missing in your code. You should be careful, this will probably cause problems in the future. Commented Jul 28, 2014 at 19:49
  • I just was being reckless getting the jsfiddle up. Sorry Commented Jul 28, 2014 at 20:52

1 Answer 1

1

You can do this if you set the on handler at the document level.

http://jsfiddle.net/fbNY9/

$(function () {

    $('#add').on("click", function () {
        addItem();
    });

    function addItem() {
        var listItem = '<li>' + '<button class="checkBtn" />' + '<button class="crossBtn" />' + '</li>';
        $('ul').append(listItem);
    }

    $(document).on("click",".crossBtn", function () {
        alert(); // Doesn't alert why not?
    });

    $(document).on("click",'.checkBtn', function () {
        alert(); // Doesn't alert why not?
    });

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

1 Comment

This is the proper way of handling the issue, it's called event delegation. You attach the event higher in the DOM and listen for the event on the proper target.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.