Archive for May, 2011

fix all submit buttons at one swell foop

May 25, 2011

The problem: my users are apparently getting clicky on me and causing multiple additions of data for us. When the application was first developed, we did not bounce-protect the buttons, because it was not a credit-card related application, and we didn’t think about it.

Techniquest you’ll learn:
1) a number of jQuery tricks
2) perhaps more deeply how Asp.Net form submit works (how it passes “event” to the server). We provide a bullet proof function to create the necessary hidden variables and add them to the DOM even if you don’t have any controls set to AutoPostback.

How to try this yourself:
ASPX and in-line Javascript
screen capture of my html
safeSubmit.js file
* we bind a javascript click event to every submit button in the current page (we’re thinking to plug this into our master page to fix the entire project)
* set_event_hidden_vars – creates EVENTTARGET and EVENTCOMMAND if they don’t already exist
* safe_submit – disables the button and communicates with the user. We put a delay in before the submit because otherwise the user wouldn’t see any of our cosmetic changes to the button.

// purpose - select all the submit buttons, and then bind a safe submit function to them
function bindEvents() {
// get an array of inputs of type submit
var btnArray = $(':submit');

for (var i = 0; i < btnArray.length; i++) {
var btn = btnArray[i];
//use jQuery to get the btn, then call bind
if (btn != null) $(btn).bind("click", safe_submit); // this syntax runs, but it doesn't pass the the this object
}

}

// purpose - if the asp.net hidden vars that simulate events are present, use them.
// otherwise, create them with the correct values
function set_event_hidden_vars(btn) {
var hdn = document.getElementById('__EVENTTARGET');
if (hdn == null) {
var shdn = '';
shdn = shdn.replace('qqq', btn.id);
var h = $(shdn);
$(document.forms[0]).append(h); // my pages are submitting from form[0]
//$('form').append(h);

var scmd = '';
var c = $(scmd);
$(document.forms[0]).append(c);
//$('form').append(c);
}
else hdn.value = btn.id;

}

// purpose - general routine to submit a button but to disable it so we don't get double clicks
function safe_submit(p) {
if (bShowAlerts > 0) alert('safe_submit');
if (p == null) {
alert('p is null');
return false;
}
var btnArray = $(this);
var btn = btnArray[0];
if (btn != null) {
// show the user that the button has changed
// $(btn).hide('slow'); // this worked
//$(btn).css("background-color", "green");
$(btn).css("border-color", "white");
$(btn).css("foreground-color", "white");
$(btn).val("Please wait a bit ...");
btn.disabled = true;

if (bShowAlerts > 0) alert('safe_submit ' + btn.id)

// the hidden vars communicate with the server
set_event_hidden_vars(btn)

setTimeout(submit_after_delay, 500);

}
else {
alert('the button was null');
return false;
}

}

function submit_after_delay() {
document.forms[0].submit();
}

Advertisements