Wednesday, September 9, 2009

Prevent repeated clicks on submit button

Scenario: The user wants to save something and hits the Save button (type=submit). The event performs an Ajax call to send the request to the server. The user, being unaware or not sure if their request is being processed or if they clicked the Save button properly, click it again, and again, causing several Ajax requests, which could be a real problem, if the update is to, for example, transfer funds to your ex-girlfriend's account

The solution: Prevent the user from being able to click the Save button or to when they do to ignore it.

$(document).ready(function() {
$("form").submit(function(e) {
if ($('form').valid()) {
$(':submit', this).each(function() {
if ($(this).attr('value') == 'Save') {
$(this).attr("disabled", "disabled").val("Saving....");
}
});
}
});
});


Couple of pointers:
  • The button being pressed is of type submit
  • The attr of the button gets disabled so the user cannot hit it again and again, and since the form is submitted there is no need for enabling it again.
  • In this example I have also overridden the value of the button to indicate that the form is being saved
  • In this example all submit buttons are impacted ($(':submit', this))
If you want to target only a specific button:

$(document).ready(function() {
$("#myButton").submit(function(e) {
$('#myButton', this).attr("disabled", "disabled").val("Processing....");
});
});



Oops, this does not work!!!!!!!!!!!!!!!!

The reason being is that the submit action is attached to the form not the "myButton". In order to perform the above and find out which button was pressed and take appropriate action do:

$("form").submit(function(e) {
if (e.originalEvent.explicitOriginalTarget.id == "myButton") {
//Do something
}

});

No comments:

Post a Comment