onblur不起作用,但onchange确实有效吗?

时间:2015-11-30 04:41:59

标签: javascript html5 forms validation

我错过了什么吗?我的onblur脚本不起作用,但是如果我将它设置为onchange,它就可以运行,我只运行这两个脚本来对几个HTML输入运行一些验证

脚本#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>

2 个答案:

答案 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>