简体   繁体   中英

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

});

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.

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.

// Page visibility :

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

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

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

        }
    });

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM