【发布时间】:2020-05-22 17:40:52
【问题描述】:
这里是 HTML 部分:
<body>
<div class="container">
<center>
<div id="error"></div>
<form align="center" id="border" style="margin-top:10%;width: 50%;">
<div>
<h1 style="color: white;margin-top: 2%;font-size:644%;">OthelO</h1>
<div><input type="text" name="name" placeholder="Name" required></div>
<div><input style="margin-top:4%;" type="email" name="email" placeholder=" Email" required></div>
<div> <input style="margin-top:4%;" type="password" name="password"placeholder=" Password" required></div>
<div> <input style="margin-top:4%;" type="password" name="password_confirmation" placeholder=" Confirm Password" required></div>
<div> <input style="margin-top:4%;" type="number" name="phone" placeholder=" Phone(optional)" required></div> <br>
<div><input type="checkbox" class="checkbox">
<h5 style="color:white;margin-top: -2%;">I agree to the terms & conditions</h5>
</div>
<button style="border-radius: 16px;" type="button" class="btn btn-primary" value="Submit">Sign Up</button>
<br><br>
</div>
</form>
</center>
</div>
</div>
</body>
每次我在浏览器上运行此表单时,即使在文本字段中没有输入任何内容,提交按钮也不会重定向到任何错误消息。
这里是 Javascript 部分:
<script type="text/javascript">
const name = document.getElementById("name");
const email= document.getElementById("email");
const password=document.getElementById("password");
const cpassword=document.getElementById("password_confirmation");
const number=document.getElementById("phone");
const form = document.getElementById("border");
const errorElement = document.getElementById("error");
form.addEventListener("Submit",(e) => {
let messages=[]
if(name.value=='' || name.value==null)
{
messages.push("Name is required");
}
if(password.value.length < 6)
{
messages.push("Password must be longer than 6 characters");
}
if(messages.length > 0)
{
e.preventDefault();
errorElement.innerText=messages.join(',');
}
})
</script>
我更喜欢在脚本标签中编写我的 Javascript,而不是为它制作一个单独的文件,我是 Web 开发的新手,我不确定脚本标签是否会在错误中产生任何差异。
【问题讨论】:
-
您确定调用了事件处理程序吗? (尝试调用 alert() 来查看);顺便说一句,事件应该在你的 addEventListener 中用大写的 S 写(应该是“提交”)
-
您的表单永远不会提交,因为您的按钮不是
type="submit"。
标签: javascript html forms validation dom