Question

I'm pretty new to jquery but I'm trying to do the following: Click a link, replaceWith() a form and click the submit in the form triggers a second jquery function and ajax call and another replaceWith().

These are the two functions

$(function addtop10fromuserpage() {
    $(".addshowtotop10").click(function () {
        var button = $(this);
        button.replaceWith('<form><input class="addtop10userinput" type="text" name="seriesname" /><input type="submit" class="button small addtop10usersubmit" value="Add" /></form>');
    });
});


$(function addtop10fromuserpageshowadd() {
    $(".addtop10usersubmit").click(function () {
        var button = $(this);

        var position = button.closest(".top-rating").find(".top-rating-text").html();
        alert('position');
    });
});

Bascially, both functions are fine if they are called separately but if I call the second function from the replacewith form, it doesn't work. Why is that?

Thanks.

Was it helpful?

Solution

Since the elements are created dynamically you need to use event delegation based handlers

$(function addtop10fromuserpage() {
    $(document).on('click', ".addshowtotop10", function () {
        var button = $(this);
        button.replaceWith('<form><input class="addtop10userinput" type="text" name="seriesname" /><input type="submit" class="button small addtop10usersubmit" value="Add" /></form>');
    });
});


$(function addtop10fromuserpageshowadd() {
    $(document).on('click', ".addtop10usersubmit", function () {
        var button = $(this);

        var position = button.closest(".top-rating").find(".top-rating-text").html();
        alert('position');
    });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top