How to force to lose focus of all fields in a form in jQuery
JavascriptJqueryLost FocusJavascript Problem Overview
When a input field changes (onchange) I trigger a function to set a variable. The only problem is that the field first has to lose focus before the variable is set and I can check if the field(s) is changed, this is what I want to do when the user clicks on a tab so I can check if the user is forgotten to submit his form in the previous tab. Ho to force lose focus of all possible fields, so first the onchange
event can take place?
Javascript Solutions
Solution 1 - Javascript
You can use this :
$(':focus').blur()
If you don't have jQuery in your site, you can replace it by :
let el = document.querySelector( ':focus' );
if( el ) el.blur();
Solution 2 - Javascript
You don't need jQuery for this; vanillaJS can do this, too.
document.activeElement.blur();
Note: Usually, I would check for null-ness before calling a method, but activeElement
will only ever return null if there is no ‹body›
node, so this direct call is pretty safe.
Solution 3 - Javascript
You can trigger a .blur()
event
$('SomeElement').blur(function () {
// do whatever
});
$('SomeElement').blur();
Solution 4 - Javascript
$(':focus').blur();
You can use this line of code and everything loses focus (jQuery)