Reputation: 38704
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?)
Upvotes: 6
Views: 22848
Reputation: 19752
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;
}
});
Upvotes: 3
Reputation: 70701
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);
}
Upvotes: 9