The blog has moved to http://jessehouse.com/ ... Many google searches point here so I am leaving it operational, but there will be no new posts.

Monday, February 16, 2009

use jquery to disable a button when clicked

jquery is such a great javascript library, the more I use it the more I like it

// in case using alongside prototype
var $j = jQuery.noConflict();
$j(document).ready(function()
{
// apply the disable onclick for buttons with css class of 'disable-on-click'
$j(".disable-on-click").bind('click', function(e) {
$j(this).attr("disabled", "true").attr("value", "Please wait...");
});
}
// if you need to re-enable a button
$j("#my_button").removeAttr('disabled').attr("value", "Submit");
// or all with a specific css class i.e. 'disable-on-click'
$j(".disable-on-click").each(function(e) {
// remove attribute and reset the display text for the button to 'Submit'
$j(this).removeAttr('disabled').attr("value", "Submit");
});
// UPDATE: this is more correct - (disabled = disabled) vs (disabled = true)
$j(this).attr("disabled", "disabled");
// and for Safari/Chrome (webkit browsers) a manual submit is needed
// after disabling the button
this.form.submit(); // note 'this' is the submit button in this case
// ***************************
// an alternate approach, disable the button when the form submits
// this is good in many situations but not all
$j(".disable-on-click").each( function() {
var thisButton = this;
$j(this.form).bind('submit', function(e) {
$j(thisButton).attr("disabled", "disabled").attr("value", "Please wait...");
});
});


NOTE: the above code snippets are untested - cut, pasted and modified from real code that was tested (and worked!)

 

CSS position:relative + position:absolute

I do alright with css positioning but I just don't do enough css to have it mastered; anyhow I needed to float an image over into the right upper corner of a form, no problem put a div at the bottom of the form with position relative and top at -xyz. this worked but was not ideal, depending on the amount of fields in the form I would have to adjust the top setting for each, also the alignment was not consistent enough across browsers, so a google search was on once again...

Came across this great post, see tab 4 "position:relative + position:absolute", using a relative div with a nested absolute div, I did not even know this was possible but it appears to work great!