当输入正确时,仍然会出现html-js无效的错误消息



我有以下带有js验证的输入字段来输入名称,当该字段为空时,会出现一条错误消息,这是我所需要的。然而,当我输入名称时,它接受了我表单中的输入,但同样的错误消息仍会短暂弹出。

function myFunction() {
let x = document.getElementsByName("first_name")[0].value;
let text;
text = "";
if (x == '' || x == null) {
text = "Input not valid";
}
document.getElementById("first_name_errors").innerHTML = text;
}
document.addEventListener('invalid', (function() {
return function(e) {
e.preventDefault();
document.getElementsByName("first_name").focus();
};
})(), true);
<input type="text" name="first_name" placeholder="first name" name class="input_fields" required>
<div class="error-message" id="first_name_errors"></div>
<input class="save_btn" type="submit" value="Save" name="save_fname" onclick="myFunction()">

我该怎么解决这个问题?

Moroever,我打算将此模板用于其他字段,如电子邮件和密码字段,假设我需要重点调整的代码的主要部分是?:

let text;
if (x == '' ||  x == null) {
text = "Input not valid";
}

非常感谢您的帮助/建议。感谢

您必须获取getElementsByName("first_name")返回的NodeList的第一个元素

像这样:

let x = document.getElementsByName("first_name")[0].value;

最新更新