最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Cancel an onBlur event in JavaScript? - Stack Overflow

programmeradmin2浏览0评论

I want to set up an onBlur event for an input element that validates the value and, if invalid, "cancels" the blur and refocusses the input. However returning false from onBlur does not cancel the onBlur the way it does with onClick. Is there a solution for this (perhaps using jQuery?)

I want to set up an onBlur event for an input element that validates the value and, if invalid, "cancels" the blur and refocusses the input. However returning false from onBlur does not cancel the onBlur the way it does with onClick. Is there a solution for this (perhaps using jQuery?)

Share Improve this question asked Nov 15, 2010 at 15:37 JoelFanJoelFan 38.7k38 gold badges141 silver badges213 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 9

I don't know of any reliable cross-browser way to do this. Usually setting a small timeout in the onblur event and calling focus() when the timer fires works.

For example:

document.getElementById('your_input_id').onblur = function() {
  var self = this;
  setTimeout(function() { self.focus(); }, 10);
}

You can call focus() in the handler.
This will sometimes help.

You can accomplish this by using jQuery's focus() function inside a zero-second timeout. Here's an example:

$('#my_input').bind('blur', function(event) {
   var $input = $(this);
   var is_input_valid = false;

   // Code to determine if input is valid
   // ...

   if (!is_input_valid) {
      setTimeout(function() {
        $input.focus();
      }, 0);
      return false;
   }

});
发布评论

评论列表(0)

  1. 暂无评论