Reputation: 347
I have a button that saves the content that a user edits. I do not want them to hit the save button multiple times because of the load it causes on the server. I want to disable the button after they click on it. Here is what I have attempted(doesn't work, though):
var active = true;
$("#save").click(function() {
if (!active) return;
active = false;
........
........
........
active = true;
The problem is that the user can still click on the element multiple times. How can I fix this problem?
Edit: Sorry, I forgot to mention that I want to enable the click after the onclick code has finished executing.
Upvotes: 3
Views: 1534
Reputation: 69905
Try this
$("#save").one('click', function() {
//this function will be called only once even after clicking multiple times
});
Upvotes: 16
Reputation: 101594
Assuming:
<input type="button" id="save" ... />
You can either do:
$('#save').click(function(){
var $save = $(this);
//
// save code
//
$save.get(0).disabled = true;
});
Which disabled the button natively, or you can use jQuery's one functionality:
$('#save').one('click',function(){
//
// save code
//
});
Which will only execute once and must be re-bound. (But if you're deciding to enable/disable based on parameters, using the disabled attribute is probably a better choice.)
Upvotes: 0
Reputation: 13907
If the element is an input you can do this really easily:
<input name="BUTTON" type="submit" value="Submit" onSubmit="document.BUTTON.disabled = true;">
That's some handy HTML Javascript integration stuff there.
Upvotes: 1
Reputation: 154818
There is a disabled
attribute: http://jsfiddle.net/uM9Md/.
$("#save").click(function() {
$(this).attr('disabled', true)
........
........
........
$(this).attr('disabled', false)
});
Upvotes: 2
Reputation: 342625
You can unbind the click handler, but I would go with .one
as per @ShankarSangoli's answer (+1).
$("#save").click(function() {
// do things
$(this).unbind("click");
});
Upvotes: 1