I've just run into an interesting case where I don't understand why this code works like that. Steps to reproduce:
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>