I created a button in HTML that is currently disabled but is supposed to become enabled after a particular textbox is found to no longer be empty. Then, the button saves the name with the score from the previously completed game on another web page. I did this by linking the button and textbox to a JavaScript file and specifying a function to do this for me. However, the button is refusing to become enabled even after the textbox is filled.
This is the code I tried:
What do you suggest I change?
function checkInput() {
var input = document.getElementById('username');
var button = document.getElementById('saveScoreBtn');
if (input.value !== '') {
button.disabled = true;
} else {
button.disabled = false;
}
}
<form class="end-form-container">
<h2 id="end-text">Enter your name below to save your score!</h2>
<input type="text" name="name" id="username"
placeholder="Enter your name!" onkeyup="checkInput()" />
<button class="btn" id="saveScoreBtn" type="submit"
onclick="saveBtn(event)" disabled>
Save
</button>
</form>
2
Answers
No need to implement custom form validation. It’s baked-into the
<form>
element.It looks like you might have mistakenly switched your conditions in your if-else statement in the JavaScript function checkInput. You set the button to be disabled if the input is not empty (input.value !== ”), which is the opposite of what you’re trying to achieve. Try switching the conditions like so:
Also, ensure that your JavaScript code is properly linked to your HTML file and that there are no errors preventing the checkInput function from running. You should see errors in your web browser’s JavaScript console if there are any.
Try this and let me know in comments.