Basic form validation
In this question, you’re going to make sure a text box isn’t empty. Complete the following steps:
Create a text input box. Write a function that turns the text box’s border red if the box is empty.
(It’s empty if the value equals "").
The border should go back to normal if the value is not empty.
When the user releases a key (onkeyup), run the function you just created.
please correct my code where I'm coding wrong?
let form = document.getElementById("form_Text").value;
document.getElementById("form_Text").onfocus = function() {
if (form == "") {
document.getElementById("form_Text").style.backgroundColor = "red";
document.getElementById("showText").innerHTML = "Form is empty";
} else {}
document.getElementById("form_Text").onkeyup = function() {
document.getElementById("form_Text").style.backgroundColor = "white";
document.getElementById("showText").innerHTML =
"Form is not Empty, No red Background";
};
};
Fill Your Form:
<input id="form_Text" type="text" />
<div id="showText"></div>
You are trying to get the input value with
let form = document.getElementById("form_Text").value;
right after the js is loaded. Therefore it will always be empty. You need to call it inside the event listener.But instead of writing two separate event listeners, you can use
input
event instead offocus
andkeyup
UPDATE
You can find the other way of binding below. Instead of using two separate events (
keyup
andfocus
), you can useoninput
event listener.Here's a SO thread comparing
keyup
andinput
events: https://stackoverflow.com/a/38502715/1331040