Conditionally enable and disable a button with JavaScript/jQuery
This post will discuss how to conditionally enable and disable a submit button in JavaScript and jQuery.
1. Using jQuery
With jQuery, you can use the .attr() method to add disabled
HTML attribute to the submit button and .removeAttr() method to remove the disabled
attribute from it. The value of the disabled
HTML attribute indicates whether the element is enabled or disabled.
The following example demonstrates this by disabling the submit button on empty input and enabling it when supplied.
JS
1 2 3 4 5 6 7 8 9 10 11 12 |
$(document).ready(function() { $('button').attr('disabled', 'disabled'); $('input[type=text]').on('input', function() { if ($(this).val() !== '') { $('button').removeAttr("disabled"); } else { $('button').attr('disabled', 'disabled'); } }); }); |
HTML
1 2 |
<input type="text" placeholder="Enter your name..."> <button>Submit</button> |
Alternatively, you can use the .prop() method to set a boolean value to the disabled
property.
JS
1 2 3 4 5 6 7 8 9 10 11 |
$(document).ready(function() { $('button').prop('disabled', true); $('input[type=text]').on('input', function() { if ($(this).val() !== '') { $('button').prop('disabled', false); } else { $('button').prop('disabled', true); } }); }); |
HTML
1 2 |
<input type="text" placeholder="Enter your name..."> <button>Submit</button> |
This can be further shortened to the following code:
JS
1 2 3 4 5 6 |
$(document).ready(function() { $('button').prop('disabled', true); $('input[type=text]').on('input', function() { $('button').prop('disabled', !$(this).val()); }); }); |
2. Using JavaScript
In plain JavaScript, the idea remains similar. We bind an event handler to the input
event using the addEventListener() method and use that handler to conditionally set a boolean value to the disabled
property.
JS
1 2 3 |
document.getElementById('name').addEventListener('input', function(event) { document.getElementById('submit').disabled = !this.value; }, false); |
HTML
1 2 |
<input id="name" type="text" placeholder="Enter your name..."> <button id="submit" disabled>Submit</button> |
That’s all about conditionally enable and disable a button in JavaScript and jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)