Javascript: how do I get the value of an input in real time?

48 views Asked by At

I am programming a web page and I have an input where the user must enter a 5-letter word and a button that will use said word for a function, I want the button to be disabled as long as 5 letters have not been entered but I don't know how to do it exactly, so I was thinking that if I could get the value of the input in real time I could try something.

I haven't tried anything yet because I don't know where to start. I know how to disable a button, I just don't know how to get the input value in real time.

1

There are 1 answers

0
hsjeevan On BEST ANSWER

HTML

   <input type="text" id="wordInput" placeholder="Enter a 5-letter word">
    <button id="submitButton" disabled>Submit</button>

JS

// Get references to the input field and submit button
const wordInput = document.getElementById('wordInput');
const submitButton = document.getElementById('submitButton');

// Add an event listener to the input field
wordInput.addEventListener('input', function () {
    const inputValue = wordInput.value.trim(); // Remove leading/trailing spaces
    const isValidWord = inputValue.length === 5; // Check if the word has 5 letters

    // Enable or disable the button based on word length
    submitButton.disabled = !isValidWord;
});