Enable/Disable Input Button Using JavaScript

  1. Use JavaScript to Enable/Disable Input Button
  2. Use jQuery to Enable/Disable Input Button

This tutorial teaches how to enable/disable an HTML input button using JavaScript/JQuery.

We often come across situations where we want to enable/disable an HTML button, like before and after submitting a form. The best way to do this is to use the JavaScript DOM Manipulation to select the button and change its disabled status to true/false to toggle its on/off state. Below, we will see two ways to disable/enable a button, one using JavaScript and the other using JQuery.

Use JavaScript to Enable/Disable Input Button

Below is the demonstration of a button getting activated when text is input in a box and deactivated otherwise.


<input class="input" type="text" placeholder="fill me">
<button class="button">Click Me</button>

JavaScript Code

let input = document.querySelector(".input");
let button = document.querySelector(".button");
button.disabled = true;
input.addEventListener("change", stateHandle);
function stateHandle() {
  if (document.querySelector(".input").value === "") {
    button.disabled = true; 
  } else {
    button.disabled = false;

disable button javascript.png

Here, we first store the reference to input and button in two variables and then set the button’s default state to disabled. We add an event listener to see if there is any input activity inside the textbox and then use the function stateHandle() to disable/enable the submit button accordingly.

Use jQuery to Enable/Disable Input Button

    <title>Enable/Disable a HTML button</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

      Name: <input type="text" id="reco" />
    <input type="submit" id="submit" disabled="disabled" />

    $(document).ready(function () {
        $('#reco').on('input change', function () {
            if ($(this).val() != '') {
                $('#submit').prop('disabled', false);
            else {
                $('#submit').prop('disabled', true);

We use the ready() function to make it available once the document has been loaded. The .on() method then attaches the event handler to the input field. The change event will check for changes in the input field and run the function accordingly. The .prop() method then changes the state of the button.

DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - JavaScript DOM

  • JavaScript DOM Ready