Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery focus not working on blur

Tags:

jquery

I am using jquery to keep the focus on a text box on blur if validation fails. But Its working in IE but not working FF. Any suggestions?

$("#inputBoxId").blur(function () {
   if ($(this).val() < 10) 
      $("#inputBoxId").focus();

});
like image 747
Manu Avatar asked Feb 24 '11 12:02

Manu


People also ask

How to bind blur event in jQuery?

$( "#field1" ). blur(function() { alert( "Lose focus from Field1" ); }); Note : In jQuery blur( handler ) method is used to bind an event handler to the "blur" JavaScript event, or trigger that event on an element.

When blur event is fired?

The blur event fires when an element has lost focus. The main difference between this event and focusout is that focusout bubbles while blur does not. The opposite of blur is focus . This event is not cancelable and does not bubble.

What is blur in jQuery?

jQuery blur() MethodThe blur event occurs when an element loses focus. The blur() method triggers the blur event, or attaches a function to run when a blur event occurs. Tip: This method is often used together with the focus() method.

What is handle blur?

handleBlur is how touched is actually updated (or at least one of the ways). If your input isn't passed an onBlur handler connecting to Formik's state, the touched state won't be updated.


2 Answers

Looks like you need to use setTimeout according to this question. Since you are giving focus to an element immediately you need to account for some time for the element to go out of focus first.

$("#inputBoxId").blur(function() {
    if ($(this).val() < 10) {
        setTimeout(function() {
            $("#inputBoxId").focus();
        }, 100);
    }
});

Example of it working on jsfiddle, tested out on chrome dev channel, firefox, and IE8.

like image 132
Mark Coleman Avatar answered Oct 11 '22 13:10

Mark Coleman


val() will return string, not number. Try converting and it should work:

var value = parseInt($(this).val(), 10);
if (isNaN(value) || value < 10) 
      $("#inputBoxId").focus();

This will also deal with non numeric values.

like image 41
Shadow Wizard Hates Omicron Avatar answered Oct 11 '22 11:10

Shadow Wizard Hates Omicron