July 26, 2013

on blur of input field validate field and cancel blur event if not valid

Xavier DSouza’s Question:

I am validating a field on blur event. And if the field is invalid I want the focus to remain in same field and not go to next field. When I do $(this).focus() within my blur function it only works in Chrome and not in Firefox. I tried the settimeout function but the problem is that the focus goes to next field(#myInput2) and then comes back to field(#myInput1). I dont want that as the next field also raises error cause it will be blurred again and it is empty. Is there a way to solve this in Firefox??
My code :

$('#myInput1').blur(function () {
    if (!validField1($(this).val())) {
        alert("Invalid");
        $(this).focus(); // Does not work in FF 
    }
});


$('#myInput2').blur(function () {
    if (!validField2($(this).val())) {
        alert("Invalid");
        $(this).focus();
    }
});

I asked this question once, these are generally browser features which is not lock down a user to one input box. User should have choice of going away if they wanted, whether or not it is valid.

So, Focus the same element after the blur event is disallowed.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!