【发布时间】:2014-10-22 17:32:41
【问题描述】:
这是我的代码。我想使用 javascript 验证表单。我想在用户专注于填写表单后验证特定的表单元素。它的发生方式是,仅加载页面就会显示十字标记,这意味着在没有用户输入代码的情况下特定表单无效。 注意:我使用 Bootstrap 作为图标 - 'Tick' 和 'X'。谢谢您的帮助。
<!DOCTYPE html>
<html>
<head>
<title> Form Elements </title>
<!-- Latest compiled and minified CSS OF BOOTSTRAP - BOOTSTRAP CDN-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<!--Script of Javascript-->
<script type="text/javascript">
ID = setTimeout("check_name();", 0);
ID = setTimeout("check_phone();", 0);
ID = setTimeout("check_address();", 0);
function check_name() {
if (document.form.name.value.length < 1) {
keycode = document.getElementById("name");
character = ' <i class="glyphicon glyphicon-remove"></i>';
keycode.innerHTML = character;
} else {
keycode = document.getElementById("name");
character = ' <i class="glyphicon glyphicon-ok"></i>';
keycode.innerHTML = character;
}
ID = setTimeout("check_name();", 500);
}
function check_phone() {
if (document.form.phone.value.length < 10) {
keycode = document.getElementById("phone");
character = ' <i class="glyphicon glyphicon-remove"></i>';
keycode.innerHTML = character;
} else {
keycode = document.getElementById("phone");
character = ' <i class="glyphicon glyphicon-ok"></i>';
keycode.innerHTML = character;
}
ID = setTimeout("check_phone();", 500);
}
function check_address() {
if (document.form.address.value.length < 1) {
keycode = document.getElementById("address");
character = ' <i class="glyphicon glyphicon-remove"></i>';
keycode.innerHTML = character;
} else {
keycode = document.getElementById("address");
character = ' <i class="glyphicon glyphicon-ok"></i>';
keycode.innerHTML = character;
}
ID = setTimeout("check_address();", 500);
}
</script>
<style>
.glyphicon {
font-size: 20px;
}
.glyphicon-remove {
color: red;
}
.glyphicon-ok {
color: green;
}
</style>
</head>
<body>
<div class="row" style="padding:20px;">
<form name="form">
<p>Name:</p>
<input type="text" onfocus="check_name();" name="name" /><span id="name"></span>
<br />
<p>Phone:</p>
<input type="text" onclick="check_phone();" name="phone" /><span id="phone"></span>
<br />
<p>Address:</p>
<input type="text" onclick="check_address();" name="address" /><span id="address"></span>
<br />
<button type="submit" onclick="test();">Submit</button>
</form>
</div>
</body>
</html>
【问题讨论】:
-
“焦点后”被称为模糊,如果这开始你的过程。
-
不,我什至试过它不工作....
-
你能解释一下你的评论吗@Teemu,:)
-
@Anivarth JS beautifier 是你的朋友; )。
-
将表单元素命名为“name”是一场等待发生的灾难。仅供参考......(另外,你在那里缺少一个空间,会造成进一步的不可预测性)
标签: javascript html twitter-bootstrap validation