I want to se开发者_如何学Ct 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 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;
}
});
精彩评论