2

im getting really crazy about this, i cant make a simple click() event in jQuery. i really need your help on this.

i have ajax that will send data to a PHP file and the result will echo back as (response)

$.post("get.php?data="+ data, {
  }, function(response){
  $('#load').html(response);

included in the response, is this <img src="next.png" id="next" alt="" />

i simply want the next image to be clickable and display some kind of alert.

below are my different variations on the code. but i still cant make the button work!

//test 1
$(document).ready(function () {
    $('#next').livequery("click", function () {
        alert("test");
    });
});

//test 2
$(document).ready(function () {
    $('#next').on("click", function () {
        alert("test");
    });
});

//test 3
$(document).ready(function () {
    $('img#next').on("click", function () {
        alert("test");
    });
});

//test 4
$(document).ready(function () {
    $('#next').on("click", "img", function () {
        alert("test");
    });
});

//test 5
$(document).ready(function () {
    $('#next').on("click", "img", function (e) {
        e.preventDefault();
        alert("test");
    });
});

1 Answer 1

2

Use .on()

As elements are added dynamically you can not bind events directly to them .So you have to use Event Delegation.

$(document).ready(function () {
    $(document).on("click", "#next", function (e) {
        e.preventDefault();
        alert("test");
    });
});

or better

$(document).ready(function () {
    $("#load").on("click", "#next", function (e) {
        e.preventDefault();
        alert("test");
    });
});

Syntax

$( elements ).on( events, selector, data, handler );
Sign up to request clarification or add additional context in comments.

1 Comment

thank you! never knew about event delegation. thanks for saving me from headache.

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.