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" />
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.
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.
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.
In jQuery by using blur() property we can remove focus from input textbox field.
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.
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; } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With