How to prevent text box losing focus with jQuery and JavaScript?
I have a <input type="text"/>
text box that I want to check when focus is lost. If the input is invalid, I want to prevent the focus from moving to the next element, or, in other words, keep the focus on the invalid input until it is valid.
How to do it using jQuery and JavaScript?
I tried with this code, but it does not work ( jsFiddle ):
<!DOCTYPE html> <html> <head> <script src="jquery-1.6.2.min.js"></script> <script> $(function() { $('.hello').bind('focusout', function(e) { if(!isValid($(this).val())) { e.preventDefault(); $(this).foucus(); } }); }); function isValid(str) { if(str === "hello") { return true; } else { return false; } } </script> </head> <body> Only valid content: <b>hello</b><br> <input type="text" class="hello"/> <button>Dummy</button> </body> </html>
This is just a typo. Change:
$(this).foucus();
To:
$(this).focus();
In addition, you may want your users to correct their mistake by also invoking select
in the text box. So they can just start typing again to change the value:
$(this).focus().select();
Here is a working example .
Note. This answer fixes the problem i.e. Asked question. On a larger scale, I agree with others who say that you should not block the user in the field. The best way to do this would be to check the entire form on the submission, allowing users to see all the problems and fix them all at once, instead of listening to them everywhere.