脚本#1的目的是检查是否有空格,表明用户输入了姓名(可能有更好的方法)
脚本#2的目的是在用户退出输入字段时检查空格是否为空白
的Javascript
// Script #1
document.getElementById('name').onchange=function() {
var theName = document.getElementById('name').value;
if (theName.indexOf(' ') <= 0) {
document.getElementById('name_error').innerHTML = "Must include first and last name";
}
}
// Script #2
document.getElementById('name').onBlur=function() {
if (document.getElementById('name').value=="") {
document.getElementById('name_error').innerHTML = "The name field is required";
}
}
HTML
<label for="name" id="name_label">Name<span class="red">* </span></label><br>
<span id="name_error" class="hint"></span>
<input type="text" name="name" id="name" pattern="[A-Za-z0-9 ]"
placeholder="Full name please" maxlength="25" autofocus required>
答案 0 :(得分:0)
您的代码中有拼写错误,只需将onBlur
替换为onblur
。
document.getElementById('name').onblur = function() {
if (document.getElementById('name').value === '') {
document.getElementById('name_error').innerHTML = 'The name field is required';
}
}
<label for="name" id="name_label">Name<span class="red">* </span></label><br>
<span id="name_error" class="hint"></span>
<input type="text" name="name" id="name" pattern="[A-Za-z0-9 ]" placeholder="Full name please" maxlength="25" autofocus required>
另请注意,使用addEventListener
函数处理DOM元素中的事件是一种更好的做法:
document.getElementById('name').addEventListener('blur', function(event) {
// your code...
});
查看this link以获取更多信息。
答案 1 :(得分:0)
您的代码中有一个拼写错误:onblur
。不是onBlur
。
document.getElementById('name').onblur=function() {
if (document.getElementById('name').value=="") {
document.getElementById('name_error').innerHTML = "The name field is required";
} else {
// do something with this 'name'
}
}
<label for="name" id="name_label">Name<span class="red">* </span></label><br>
<span id="name_error" class="hint"></span>
<input type="text" name="name" id="name" pattern="[A-Za-z0-9 ]"
placeholder="Full name please" maxlength="25" autofocus required>