Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

182
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda