jquery enable submit button
- Published
- Reading time
- 1 min read
- Length
- 290 words
On this page
How to Enable Submit Button using jQuery#
Have you ever encountered a situation where you have a form with a disabled submit button and you want to enable it dynamically based on some condition? Well, you can easily achieve this using jQuery.
Method 1: Using the prop() Method#
The prop() method sets or returns properties and values of the selected elements. We can use it to enable or disable the submit button based on some condition.
$(document).ready(function(){
$('#myForm').submit(function(){
if(condition){
$('#submitBtn').prop('disabled', false);
} else {
$('#submitBtn').prop('disabled', true);
}
});
});- The code above uses the
submit()method to attach an event handler to the form submit event. - It then checks for a certain condition and enables/disables the submit button using the
prop()method. - The
truevalue passed as the second parameter disables the button whereasfalseenables it.
Method 2: Using the attr() Method#
The attr() method is used to get or set attributes and their values of the selected elements. In this case, we will use it to enable or disable the submit button by setting its disabled attribute.
$(document).ready(function(){
$('#myForm').submit(function(){
if(condition){
$('#submitBtn').removeAttr('disabled');
} else {
$('#submitBtn').attr('disabled', 'disabled');
}
});
});- The code above uses the
submit()method to attach an event handler to the form submit event. - It then checks for a certain condition and enables/disables the submit button using the
removeAttr()andattr()methods respectively. - The
removeAttr('disabled')method removes thedisabledattribute from the button whereasattr('disabled', 'disabled')sets it to'disabled'.
Both methods work just fine. However, the prop() method is recommended over the attr() method for handling boolean attributes such as disabled.
I hope this helps you enable your submit button dynamically using jQuery.