我正在编写一个网页,我有一个输入,用户必须输入 5 个字母的单词和一个按钮,该按钮将使用所述单词作为功能,我希望只要未输入 5 个字母,就禁用该按钮但我不知道具体该怎么做,所以我想如果我能实时获取输入的值我可以尝试一些东西。
我还没有尝试过任何事情,因为我不知道从哪里开始。我知道如何禁用按钮,只是不知道如何实时获取输入值。
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;
});