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 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.