简体   繁体   中英

How to detect if user has left the input field?

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?

Normal 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.org/en-US/docs/Web/Events/blur

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM