kopaty4
kopaty4

Reputation: 2296

JQuery - button from ajax

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.

Upvotes: 0

Views: 2619

Answers (4)

matt
matt

Reputation: 9401

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/

Upvotes: 1

Chad Ruppert
Chad Ruppert

Reputation: 3680

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.

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816452

$("#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');
});

Upvotes: 2

Richard Dalton
Richard Dalton

Reputation: 35793

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.

Upvotes: 1

Related Questions