我是JavaScript的新手,我正在尝试在我的注册表单上实现客户端验证。目标是当用户按下提交按钮时,错误被设置为可见性:可见。但是这不起作用。我的代码出了什么问题?
function validate() {
var errorname = document.getElementById("errorforename");
var user_forename = document.register.user_forename;
if (user_forename === "") {
errorforename.style.visibility = "visible";
}
}
.error {
color: red;
font-style: italic;
font-size: 17px;
visibility: hidden;
}
<form id="register" name="register" action="#" method="post">
<label for="forename">Forename</label>
<input type="text" id="forename" name="user_forename" placeholder="John" required>
<span id="errorforename" class="error">First name is required</span>
<button type="submit" value="Submit" onclick="validate();">Register</button>
</form>
答案 0 :(得分:1)
document.register.user_forename
是元素。要阅读其值,您需要添加.value
。
答案 1 :(得分:1)
在 document.register.user_forename 之后添加 .value ,
像这样,var user_forename = document.register.user_forename.value;