How to Disable a Button in Javascript Based On Condition

In this tutorial, you will learn how to disable a button in javascript based on condition. The button element is commonly used to perform some sort of form data submission to the server.  It is common practice to perform client-side validation first and show the errors on screen if any.  In the meanwhile, you can keep submit button disabled.

The best part of using javascript is here that you can dynamically enable or disable the button element using disabled property depending upon a certain condition.

In the following example, we have an input field where we will enter some random string and if the length of the string is greater than 6, then we will disable the button element.  Please have a look over the code example and the steps given below.

HTML & CSS

  • We have a few elements in the HTML file and that includes div, input, button, and h1. The div element is just a wrapper for the rest of the elements.
  • The inner text for the button element is “Show” and for the h1 element, it is “Your Name”.
  • We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
  • We have also included our javascript file script.js with a script tag at the bottom.
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="style.css">
  <title>Document</title>
</head>
<body>
    
  <div>
    <input type="text" placeholder="Enter Your Name">
    <button>Show</button>
    <h1>Your Name</h1>
  </div>

  <script src="script.js"></script>
</body>
</html>
div {
    margin: auto;
    width: 20%;
}

Javascript

  • We have selected 3 elements button, input, and h1 using document.querySelector() method and stored them in btnShow, input, and output variables respectively.
  • We have attached the click event listener to the button element.
  • In the click event handler function, we are getting the value of the input element and setting it as the innerText of the h1 element.
  • We have attached the keyup event listener to the input element.
  • In the keyup event handler function, we are checking if the length of the string entered in the input element is greater than 6 or not. If yes, then we are disabling the button element using the disabled property by setting it to True.  If not, we are setting the disabled property to False.
let btnShow = document.querySelector('button');
let input = document.querySelector('input');
let output = document.querySelector('h1');

btnShow.addEventListener('click', () =>{
    output.innerText = input.value;
});

input.addEventListener('keyup', () =>{
    
    if(input.value.length > 6) btnShow.disabled = true
    else btnShow.disabled = false;
});
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •