Required field in form doesn´t change to red after erasing input content

583 Views Asked by At

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>

1

There are 1 best solutions below

3
On BEST ANSWER

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.

document.getElementById("form_Text").onfocus = function() {
    let form = document.getElementById("form_Text").value;
    ...
}

But instead of writing two separate event listeners, you can use input event instead of focus and keyup

   
const formText = document.getElementById("form_Text");
const showText = document.getElementById("showText");

formText.addEventListener('input', function(evt) {
  const inputValue = evt.target.value;

  if (inputValue == '') {
    formText.style.backgroundColor = "red";
    showText.innerHTML = "Form is empty";
  } else {
    formText.style.backgroundColor = "white";
    showText.innerHTML = "Form is not Empty, No red Background";
  }
})
Fill Your Form:
<input id="form_Text" type="text" />
<div id="showText"></div>


UPDATE

You can find the other way of binding below. Instead of using two separate events (keyup and focus), you can use oninput event listener.

Here's a SO thread comparing keyup and input events: https://stackoverflow.com/a/38502715/1331040

const formText = document.getElementById("form_Text");
const showText = document.getElementById("showText");


formText.oninput = function(evt) {
  const inputValue = evt.target.value;

  if (inputValue == '') {
    formText.style.backgroundColor = "red";
    showText.innerHTML = "Form is empty";
  } else {
    formText.style.backgroundColor = "white";
    showText.innerHTML = "Form is not Empty, No red Background";
  }
}
Fill Your Form:
<input id="form_Text" type="text" />
<div id="showText"></div>