我有一个文本框,我用JS查看文本框是否为空。 如果为空,则会在文本框下方显示错误消息。
现在,当我返回并在空文本框中输入文本时,错误消息仍然存在。如何重新检查用户是否输入了任何文本,然后自动删除错误链接。
<label for="last_name_field">Last Name <abbr title="Required">*</abbr></label>
<input type="text" id="last_name_field" name="lastname" placeholder="Last Name" onblur="validateLN()">
&#13;
function validateLN() {
if (document.form.lastname.value == "") { //create an error message
var msg = " Last Name cannot be blank";
//call the display error function
displayError(document.form.lastname, msg);
}
}
function displayError(element, msg) {
if (element.nextSibling.tagName == "SPAN" && element.nextSibling.textContent.trim == msg.trim) {
return;
} else {
var msgElement = document.createElement("span");
msgElement.textContent = msg;
msgElement.style.color = "red";
element.parentNode.insertBefore(msgElement, element.nextSibling);
element.style.border = "solid 1px red";
}
}
&#13;
答案 0 :(得分:0)
从文本框的onchange
事件中删除错误。
function validateLN() {
if (document.form.lastname.value == "") { //create an error message
var msg = " Last Name cannot be blank";
//call the display error function
displayError(document.form.lastname, msg);
}
}
document.form.lastname.onchange = function() {
document.getElementById('errorMsg').remove();
}
function displayError(element, msg) {
if (element.nextSibling.tagName == "SPAN" && element.nextSibling.textContent.trim == msg.trim) {
return;
} else {
var msgElement = document.createElement("span");
msgElement.id = 'errorMsg';
msgElement.textContent = msg;
msgElement.style.color = "red";
element.parentNode.insertBefore(msgElement, element.nextSibling);
element.style.border = "solid 1px red";
}
}
或者只是将其保留在那里并切换其display
值:
var msgElement = document.createElement("span");
msgElement.id = 'errorMsg';
msgElement.textContent = msg;
msgElement.style.color = "red";
msgElement.style.display = 'none';
element.parentNode.insertBefore(msgElement, element.nextSibling);
element.style.border = "solid 1px red";
function validateLN() {
if (document.form.lastname.value == "") { //create an error message
var msg = " Last Name cannot be blank";
//call the display error function
document.getElementById('errorMsg').style.display = 'inline';
}
}
document.form.lastname.onchange = function() {
document.getElementById('errorMsg').style.display = 'none';
}