Manu
Manu

Reputation: 191

jquery focus not working on blur

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();

});

Upvotes: 7

Views: 5494

Answers (4)

Ajay Kumar
Ajay Kumar

Reputation: 1

// Page visibility :

    document.addEventListener('visibilitychange', function () {

        if (document.hidden) {
            // stop running expensive task

        } else {
            // page has focus, begin running task

        }
    });

Upvotes: 0

Mark Coleman
Mark Coleman

Reputation: 40863

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.

Upvotes: 14

S L
S L

Reputation: 14318

$(this).val().length will also give the length

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

Upvotes: 0

Shadow Wizard
Shadow Wizard

Reputation: 66389

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.

Upvotes: 1

Related Questions