Home > other >  html js not valid error message still appearing when input is correct
html js not valid error message still appearing when input is correct

Time:12-07

I have the following input field with js validation to input a name and when the field is left blank an error message appears which is what I required however when I enter a name it accepts the input in my form however the same error message pops up stil briefly.

function myFunction() {

  let x = document.getElementsByName("first_name").value;

  let text;
  if (x == '' || x == null) {
    text = "Input not valid";
  }
  document.getElementById("first_name_errors").innerHTML = text;
}

document.addEventListener('invalid', (function() {
  return function(e) {
    e.preventDefault();
    document.getElementsByName("first_name").focus();
  };
})(), true);
<input type="text" name="first_name" placeholder="first name" name class="input_fields" required>
<div class="error-message" id="first_name_errors"></div>
<input class="save_btn" type="submit" value="Save" name="save_fname" onclick="myFunction()">
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

How can i fix this?

Moroever, I intend to use this template for other fields such as email and password fields assuming that the main part of this code I need to focus adapting is?:

let text;
  if (x == '' ||  x == null) {
    text = "Input not valid";
  }

Help/advice is much appreciated. Thanks

CodePudding user response:

You have to take the first element of the NodeList returned by getElementsByName("first_name")

Like this:

let x = document.getElementsByName("first_name")[0].value;
  • Related