tags:

views:

71

answers:

1

I subscribe to the click event on all submit buttons on my page once loaded. All buttons fire off the correct event when clicked, but this only works once. If you click any two buttons in a row the second button submits the form normally as opposed to running the script. What am I doing wrong?.

Note: I load the form data from "myurl" using .load() then hook up to the submit buttons' click events in the complete event.

$(document).ready(function()
{
    //Load user content
    $("#passcontent").load("myurl", function()
    {
        //subscribe to click events for buttons to post the data back
        $('input[type=submit]').click(function()
        {
            return submitClick($(this));
        });
    });
});

function submitClick(submitButton)
{
    submitButton.attr("disabled", true);

    alert(submitButton.closest("form").serialize());
    $.post("myurl",
            submitButton.closest("form").serialize(),
            function(data)
            {
                alert("woop");
                $("#passcontent").html(data);
            });

    //Prevent normal form submission process from continuing
    return false;
}
A: 

I would rearrange your click handler like this:

$(function() {
  $("#passcontent").load("myurl");

  $('input[type=submit]').live('click', function() {
    $(this).attr("disabled", true);        
    $.post("myurl", $(this).closest("form").serialize(), function(data) {
       $("#passcontent").html(data);
    });
    return false;
  });
});

Using .live('click', func) listens for current and new elements' click events since they bubble up the DOM the same way. By doing the above, you're attaching one handler at the root of the DOM listening for any input[type=submit] to bubble a click up, making it work even when you reload the content and the submit button is replaced.

Nick Craver