Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery focus not working

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

$('#cc_number').validateCreditCard(function (result) {
    if (result.length_valid && result.luhn_valid) {

    } else {
       $("#cc_number").focus();
       return false;
    }
});

<input  type="text" id='cc_number' name="cc_number" />
like image 639
Naresh Avatar asked Aug 22 '13 14:08

Naresh


People also ask

Is Focus deprecated in jQuery?

If jQuery UI is not loaded, calling the . focus() method may not fail directly, as the method still exists. However, the expected behavior will not occur. This method is deprecated.

How does focus work in jQuery?

The focus event occurs when an element gets focus (when selected by a mouse click or by "tab-navigating" to it). The focus() method triggers the focus event, or attaches a function to run when a focus event occurs. Tip: This method is often used together with the blur() method.

What is focus () JavaScript?

JavaScript | Focus() JavaScript focus method is used to give focus to a html element. It sets the element as the active element in the current document. It can be applied to one html element at a single time in a current document. The element can either be a button or a text field or a window etc.

How Stop focus in jQuery?

In jQuery by using blur() property we can remove focus from input textbox field.


2 Answers

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.

like image 71
Curtis Avatar answered Oct 11 '22 12:10

Curtis


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

like image 41
Shoaib Chikate Avatar answered Oct 11 '22 12:10

Shoaib Chikate