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

179
Views
Js works definitely on the same code with regex

I've just run into an interesting case where I don't understand why this code works like that. Steps to reproduce:

  1. Copy mail from the existing div I hardcoded
  2. Insert into the email field
  3. Click once or two times on the "Add" button

Expected:

New divs should have been added without highlighting the input

Actual:

It adds new div but second time it highlights input field

Why? I tried to log those values but still don't understand LOOK FULL EXAMPLE ON

const el = document.getElementById('emails');
const input = document.getElementById('input')
let reg = /^(\w|\-)+@[a-zA-Z0-9][-_.}?+[a-zA-Z]+\.[a-z]{2,4}$/gi
let prevVal = input.value;

function myFunction() {
  const inputVal = input.value;
  const isInvalid = !reg.test(inputVal);
  console.log('val:', inputVal, isInvalid, prevVal === inputVal)
  if (isInvalid) {
    console.log('Wrong email');
    input.style.borderColor = 'red';
  } else {
    const newDiv = document.createElement('div');
    newDiv.innerText = inputVal;
    newDiv.classList.add('email')
    el.appendChild(newDiv);
  }
  prevVal = inputVal
}
button {
  border: 2px solid black;
  border-radius: 10px;
  padding: 10px 40px;
  cursor: pointer;
}

.email {
  border: 2px solid black;
  padding: 5px 8px;
  margin: 10px 0;
  cursor: pointer;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <link rel="stylesheet" href="stylejs.css">
</head>

<body>
  <div>
    <input type="text" id="input">
    <button onclick="myFunction()">ADD</button>
    <!-- inputs -->

    <div id="emails">
      <div class="email">mail@mail.ru</div>
    </div>
  </div>
  <script src="indexjs.js"></script>
</body>

</html>

about 4 years ago · Santiago Gelvez
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!