0

I`m from Russia, so sorry for bad English. I am loading a part of webpage with ajax.

for example

<script type="text/javascript">
$("#link1").click(function(){
    $.post("ajax.php", { act: "load" },
    function(data) {
        $("#content").html(data);
    });
});
</script>

<a href="#" id="link1">Click</a>
<div id="content"></div>

Ajax.php returns: <input type="button" id="button1" value="test">

Now I want to control this button from script too. I`m trying:

<script type="text/javascript">
    $("#link1").click(function(){
        $.post("ajax.php", { act: "load" },
        function(data) {
            $("#content").html(data);
        });
    });

    $("#button1").click(function(){
        alert('test');
    });
</script>

but this doesn`t work. Can you help me? Thanks.

4 Answers 4

2
$("#button1").click(...);

won't do anything because the element #button1 does not exist yet when you run that code ($("#button1") will not select any element).

Either put it in the callback of your Ajax request:

$.post("ajax.php", { act: "load" }, function(data) {
    $("#content").html(data);
    $("#button1").click(function(){
        alert('test');
    });
});

or use .delegate() / .live():

$("#content").delegate('#button1', 'click', function(){
    alert('test');
});
Sign up to request clarification or add additional context in comments.

Comments

1

Change it to use:

$("#button1").live('click', function(){
    alert('test');
});

The live function allows events to be fired from elements that are dynamically added to the page.

Comments

1

this part:

$("#button1").click(function(){
    alert('test');
});

is attaching the click handler to any existing dom elements with the Id button1 when the script is first run. Since that button doesn't exist until you manually click on your link1 element, you need to change how you're adding the event handler. Try using the live method from jquery to do this:

<script type="text/javascript">
    $("#link1").click(function(){
        $.post("ajax.php", { act: "load" },
        function(data) {
            $("#content").html(data);
        });
    });

    $("#button1").live('click', function(){
        alert('test');
    });
</script>

This will attach the event handler to any matching elements as soon as they become "live" in the document. More here: http://api.jquery.com/live/

Comments

0

You are registering the click event for any buttons that are currently on page. By the time your link has been clicked, its already been registered.

Use the live event as mentioned by Richard D. That sets the event for any buttons that ever match the id you are using as your selector.

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.