最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to detect if user has left the input field? - Stack Overflow

programmeradmin1浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 8

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

发布评论

评论列表(0)

  1. 暂无评论