提交电子邮件验证时不会添加 innerHTML



如果有人在表单中输入了不正确的电子邮件,我正在尝试操纵 DOM。 发生的情况是页面上似乎没有发生任何事情。 下面是我的 html 代码。

function ValidateEmail(inputText) {
var mailformat = /^w+([.-]?w+)*@w+([.-]?w+)*(.w{2,3})+$/;
if (inputText.value.match(mailformat)) {
alert("You have entered a correct email addresss")
document.form1.text1.focus();
return true;
} else {
document.getElementById("addedText").innerHTML += " this has just been added";
// alert("You have entered an invalid email address!");
document.form1.text1.focus();
return false;
}
}
<div class="email-entry desktop-container">
<div id="a"></div>
<form name="form1" action="#">
<input id="test" type="text" name="text1" value="" placeholder="Email Address">
<input type="image" value="validate" onclick="ValidateEmail(document.form1.text1)" src="images/icon-arrow.svg" alt="submit">
<p id="addedText"></p>
</form>
</div>

当我添加警报时,它似乎有效。 不确定我在定位元素时做错了什么。

当您单击图像时,它的作用类似于提交按钮并提交表单。您不会取消点击。您在单击时缺少返回,因此忽略return false

function ValidateEmail(inputText) {
var mailformat = /^w+([.-]?w+)*@w+([.-]?w+)*(.w{2,3})+$/;
if (inputText.value.match(mailformat)) {
alert("You have entered a correct email addresss")
document.form1.text1.focus();
return true;
} else {
document.getElementById("addedText").innerHTML += " this has just been added";
// alert("You have entered an invalid email address!");
document.form1.text1.focus();
return false;
}
}
<div class="email-entry desktop-container">
<div id="a"></div>
<form name="form1" action="#">
<input id="test" type="text" name="text1" value="" placeholder="Email Address">
<input type="image" value="validate" onclick="return ValidateEmail(document.form1.text1)" src="images/icon-arrow.svg" alt="submit">
<p id="addedText"></p>
</form>

最新更新