0

I am using the .Append() method of JQuery to append buttons to an unordered list, and for some reason the appended button will not call its function when clicked. I inserted the same button using HTML, and it worked fine, but for some reason the appended button will not run. Is there a way to get them to work, or do I just have to work around it?

    $("#requestDisplay").append(<button class='requestRemovalButton'>" + "Remove Request" + "</button>);

Vs in the HTML

    <button class="requestRemovalButton">Remove Request</button>

The latter will run the function, however the former will not work, here is the function I was using to test the buttons.

    $(".requestRemovalButton").on( "click", remove);

    function remove() {
        alert( "The request is being removed, please wait." );
    }

Thanks for any advice you may have.

2
  • 1
    The way you're calling .on() will only add the event listener to .requestRemovalButton elements that exist at the point you call .on(). Commented Nov 20, 2013 at 14:08
  • 1
    I don't know if it's a copypaste error, but your code is missing some quotes. It should be .append("<button class='requestRemovalButton'>" + "Remove Request" + "</button>"); (so there's a quote before the opening <button and after the </button>) Commented Nov 20, 2013 at 14:09

2 Answers 2

7

Since the button is added dynamically, you need to use event delegation to register the event handler like:-

// New way (jQuery 1.7+) - .on(events, selector, handler)
$('#requestDisplay').on('click', '.requestRemovalButton', function(event) {
    event.preventDefault();
    alert( "The request is being removed, please wait." );
});
Sign up to request clarification or add additional context in comments.

2 Comments

I changed the format, but it still isn't working for the appended buttons. For clarification, when clicking the appended buttons, instead of giving the alert, it just refreshes the page. Edit: Nevermind, it is working, I was just clicking the wrong button. Thanks for the help!
It seems to working. Please have a look at this Fiddle Demo. I think you need to use event.preventDefault() here to prevent refreshing the page.
2

I tend to favor creating proper elements with event handlers :

var button = $('<button />', {
    'class' : 'requestRemovalButton',
    text    : 'Remove Request',
    on      : {
           click: remove
    }
});

$("#requestDisplay").append(button);

and it the button is inside a form, you have to prevent the default action of submitting that form:

function remove(e) {
    e.preventDefault();
    alert( "The request is being removed, please wait." );
}

Comments

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.