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
, andh1
. Thediv
element is just a wrapper for the rest of the elements. - The inner text for the
button
element is“Show”
and for theh1
element, it is“Your Name”
. - We have done some basic styling using CSS and added the link to our
style.css
stylesheet inside thehead
element. - We have also included our javascript file
script.js
with ascript
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
, andh1
usingdocument.querySelector()
method and stored them inbtnShow
,input
, andoutput
variables respectively. - We have attached the
click
event listener to thebutton
element. - In the
click
event handler function, we are getting the value of theinput
element and setting it as theinnerText
of theh1
element. - We have attached the
keyup
event listener to theinput
element. - In the
keyup
event handler function, we are checking if the length of the string entered in theinput
element is greater than 6 or not. If yes, then we are disabling thebutton
element using thedisabled
property by setting it toTrue
. If not, we are setting the disabled property toFalse
.
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; });