[英]Validation in JavaScript - how to make the red border disappear?
At the moment, when a field is empty and not valid the field turns red and a describing text shows up.目前,当一个字段为空且无效时,该字段变为红色并显示描述文本。 But how do I make the field and text disappear when the user fill in the field correctly?但是,当用户正确填写字段时,如何使字段和文本消失?
code in HTML: HTML 中的代码:
<label for="email"><b>Email</b></label>
<label id="lblemail" style="color: red; visibility: hidden; float: right;">Invalid email</label><br>
<input type="text" placeholder="Enter Email" name="email" id="email"><br>
code in JS: JS中的代码:
var email = document.getElementById("email");
if (email.value.trim() == "") {
email.style.border = "solid 1px red"
document.getElementById("lblemail").style.visibility="visible";
return false;
} else {
return true; }
You should add event listener on input event:您应该在输入事件上添加事件监听器:
const email = document.getElementById('email');
const label = document.getElementById('lblemail');
email.addEventListener('input', function(e) {
if (!e.target.value.trim()) {
email.style.border = 'solid 1px red';
label.style.visibility = 'visible';
} else {
email.style.border = 'solid 1px black';
label.style.visibility = 'hidden';
}
})
It's better to use input event because it checks input each time you change it最好使用输入事件,因为它会在您每次更改输入时检查输入
I think you can unset using js code我认为你可以使用 js 代码取消设置
var email = document.getElementById("email");
if (email.value.trim() == "") {
email.style.border = "solid 1px red"
document.getElementById("lblemail").style.visibility="visible";
return false;
} else {
email.style.border = "none"
document.getElementById("lblemail").style.visibility="hidden";
return true;
}
i think you can use a eventlistener, this should work我想你可以使用事件监听器,这应该可以
var email = document.getElementById("email");
email.addEventListener('change', () => {
if (email.value.trim() == "") {
email.style.border = "solid 1px red"
document.getElementById("lblemail").style.visibility="visible";
return false;
} else {
email.style.border = none;
document.getElementById("lblemail").style.visibility="visible";
return true; }
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.