Is there a more concise jQuery syntax to disable a submit button on form submit?
I have the following code to disable a su开发者_StackOverflowbmit button when the form is submitted:
$('#myform').submit(function(){
$('input[type=submit]', this).attr('disabled', 'disabled');
});
Is there a more concise syntax for this?
jQuery disable plugin.
$('input').disable(); //disables
$('input').enable(); //enables
$('input').toggleDisabled(); //toggles
$('input').toggleEnabled(); //toggles
$('input').toggleDisabled(true); //disables
$('input').toggleEnabled(true); //enables
Or, if you don't want a plugin, you can use this:
jQuery.fn.disable = function() {
$( this ).prop( "disabled", true );
};
$('input[type=submit]', this).disable();
Well, I'd give it an ID, first of all, otherwise you'll disable every submit button, which may or may not be what you intend.
Other than that, that's about it unless you want to use the disable plugin.
$('#myform').submit(function(){
$('input[type=submit]', this).prop('disabled', true);
});
It can't get more concise than this. It is clean enough. I changed $.attr()
with $.prop()
, because this is what you should use to set and get values, which change the state of an element, but not the attribute itself.
From the docs:
The
.prop()
method should be used to set disabled and checked instead of the.attr()
method.
One cleaner version can be this:
$(this).find(':submit').attr('disabled', true);
also
$(this).find(':submit').prop('disabled', true);
精彩评论