Suppose I have an input field,
<input id="city" placeholder="city">
and I want to detect whenever user leaves this field. How can I do so?
Suppose I have an input field,
<input id="city" placeholder="city">
and I want to detect whenever user leaves this field. How can I do so?
Share Improve this question edited Mar 4, 2020 at 14:00 halfer 20.5k19 gold badges109 silver badges202 bronze badges asked Oct 23, 2015 at 21:41 user379888user379888 4-
1
JS event:
onblur
w3schools./jsref/event_onblur.asp – CollinD Commented Oct 23, 2015 at 21:43 -
4
$('#city').on('blur', function() { ... })
, this should be trivial to figure out by searching Google or reading the documentation – adeneo Commented Oct 23, 2015 at 21:43 -
I can't just think of any use of
blur
that won't go on user's nerves. – Tomáš Zato Commented Oct 23, 2015 at 21:58 - thanks adeneo. i need to put this in one of the input fields to check if there is a data. – arn-arn Commented May 3, 2016 at 15:49
2 Answers
Reset to default 8Normal javascript
var element = document.getElementById("ELEMENT_ID");
element.addEventListener("blur", function() { ... your code here ...});
jQuery
$("#ELEMENT_ID").on("blur", function() { ... your code here ...});
If, by any chance, you're implementing those self-emptying fields with predefined text, use placeholder
attribute. If you're changing style based on focus, use :focus
CSS selector. Also, change
event is emitted if user leaves the field and changed it's contents.
When an element loses focus, the onblur
event is fired.
var elem = document.getElementById('city');
elem.addEventListener("blur", function( event ) {
console.log('Elvis has left the city (input)!');
}, true);
https://developer.mozilla/en-US/docs/Web/Events/blur