jQuery focus not working

前端 未结 2 1528
野性不改
野性不改 2021-01-01 09:39

I am trying to focus on credit card validation fail. but strange focus() not working.

$(\'#cc_number\').validateCreditCard(function (result) {
         


        
相关标签:
2条回答
  • 2021-01-01 10:08

    As mentioned in the comments, your original jsfiddle contains the solution.

    A workaround is to put a timeout on the focus call.

    setTimeout(function(){
        $("#cc_number").focus();
    }, 0);
    

    I'm not 100% sure, but it could be that as the alert is called on blur, you're never actually allowing the textbox to lose focus, and therefore when focus is called, it already has it.

    By using a timeout, you are putting the logic into a seperate thread, which runs seperate to the main javascript code (much like a callback function).


    But as your question comments also mention, forcing focus until validation passes is annoying.

    But this is more of a UX criticism.

    0 讨论(0)
  • 2021-01-01 10:29

    Your DOM may be getting refresh so focus is not working here. Instead you can follow this approach:

    $('#cc_number').validateCreditCard(function (result) {
        if (result.length_valid && result.luhn_valid) {
    
       } else {
          $("#cc_number").attr("autofocus","autofocus")
          return false;
       }
    });
    

    0 讨论(0)
提交回复
热议问题