【发布时间】:2020-11-15 07:29:36
【问题描述】:
如果必填字段留空,我想显示必填错误消息。我使用以下方式实现它,但是每次调用函数 checkinput() 时,它都会添加一个新的 span 元素,因此会多次输出“必需”消息。我希望 span 元素添加一次并在用户填写要求时消失。这是我的代码。
const checkinput=(event)=>{
if(event.target.value===""){
event.target.insertAdjacentHTML('afterend','<span class="text-danger">Required</span>')
}
if(event.target.value!==""){
var child=document.querySelector('span');
child.remove();
}
}
document.getElementById("username").addEventListener('blur',checkinput);
document.getElementById("password").addEventListener('blur',checkinput);
document.getElementById("confirmPassword").addEventListener('blur',checkinput);
【问题讨论】:
-
试试 jquery 验证器,它很容易处理可选、必填字段,并且您不需要为错误消息创建元素。 jqueryvalidation.org/documentation
标签: javascript html css forms validation