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?
Asked
Active
Viewed 8.7k times
55

MAXE
- 4,978
- 2
- 45
- 61

Jilco Tigchelaar
- 2,065
- 8
- 31
- 51
-
4`document.body.focus()` – adeneo May 27 '13 at 19:37
4 Answers
112
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();

Karl-André Gagnon
- 33,662
- 5
- 50
- 75
-
-
-
1
-
4or as a safe one-liner: `document.querySelectorAll(':focus').forEach(el => el.blur());` – Sjors Ottjes Jan 04 '19 at 16:28
-
`querySelectorAll`? Is it possible for more than one element to have the focus? – WoodrowShigeru Jun 08 '19 at 13:31
16
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.

WoodrowShigeru
- 1,418
- 1
- 18
- 25
4
You can trigger a .blur()
event
$('SomeElement').blur(function () {
// do whatever
});
$('SomeElement').blur();

frenchie
- 51,731
- 109
- 304
- 510
-
1$('*:focus').blur() bacause texteraes and contentEditable elements can be focused too... – mr_app May 27 '13 at 19:25
1
$(':focus').blur();
You can use this line of code and everything loses focus (jQuery)

marc_s
- 732,580
- 175
- 1,330
- 1,459

AHeraldOfTheNewAge
- 71
- 5