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


HTML



Edit in JSFiddle

 
Alternatively, you can use the .prop() method to set a boolean value to the disabled property.

JS


HTML



Edit in JSFiddle

 
This can be further shortened to the following code:

JS



Edit in JSFiddle

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


HTML



Edit in JSFiddle

That’s all about conditionally enable and disable a button in JavaScript and jQuery.