Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

157
Views
html js not valid error message still appearing when input is correct

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")[0].value;

  let text;
  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()">

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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;
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!