Web Tips
Sharing our knowledge of CFML & jQuery and many other web development tips.
Sharing our knowledge of CFML & jQuery and many other web development tips.
I recently ran across a situation in which I needed to disable a submit button after it was clicked to avoid duplicate submits of the form. This in itself seemed a pretty simple task to do with jQuery.
I soon learned that the task would be more difficult then I had anticipated. I started the task by using something similar to this.
jQuery(document).ready( function() {<br />
jQuery('form').submit(function(){<br />
// On submit disable its submit button<br />
jQuery('input:submit', this).attr('disabled', 'disabled');<br />
});<br />
});
I tested and thought all would be good, only it was not. After some double checking of my spelling, I decided to just output the value of the ‘input:submit’. I was surprised to see that it was returning ‘undefined’ as the value.
A few minutes later I find myself scrambling through Google searches and trying different bits of code, none of which was working for me. The task was only suppose to last a few minutes and now I find myself having spent a few hours trying to figure this out. Time for a lunch break.
While on break I decided, how about just figure this out on your own instead of trying to hack someone other developers code. Off to jQuery documentation I went and the first thing I was reminded of was that .each() returns an index. Assuming all of my forms have some type of element with type=submit, I can use this.
The first step was to loop through each form element on page load:
jQuery('form').each(function(formIndex) {});
Now inside of that each loop, lets add some logic:
jQuery(this).submit(function() {<br />
jQuery('input:submit').eq(formIndex).attr('disabled', 'disabled');<br />
});
This did the trick. I was now able to disable just the one form. Now if I was using this on AJAX script I would just add a return false. Here is the entire code, assuming we are making this an AJAX call.
jQuery(document).ready(function() {<br />
//Disable all form submit button on click?<br />
jQuery('form').each(function(formIndex) {<br />
jQuery(this).submit(function() {<br />
jQuery('input:submit').eq(formIndex).attr('disabled', 'disabled');<br />
return false;<br />
});<br />
});<br />
});