Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to catch moment input box lost focus?

I am using the event listener structure like below to do some stuff when the input box loses focus.

But it won't work. What event should I listen to, to get the moment the input box loses the cursor inside it (i.e. user clicks outside of it)?

document.getElementById('div inside which input is located')
    .addEventListener( 'blur',  function(e){
        if(event.target.className=='editInput'){
            doStuff(event.target);
        }
     } , false );
like image 333
lwiii Avatar asked Dec 02 '12 10:12

lwiii


People also ask

How do you know if an element loses focus?

The onfocusout event occurs when an element is about to lose focus. Tip: The onfocusout event is similar to the onblur event. The main difference is that the onblur event does not bubble. Therefore, if you want to find out whether an element or its child loses focus, you should use the onfocusout event.

How do you know if input field is focused?

To detect if the element has the focus in JavaScript, you can use the read-only property activeElement of the document object. const elem = document. activeElement; The activeElement returns the currently focused element in the document.

Which event fires whenever a control loses focus?

The onblur event occurs when an object loses focus.

How do you set focus on input tag?

To set focus to an HTML form element, the focus() method of JavaScript can be used. To do so, call this method on an object of the element that is to be focused, as shown in the example. Example 1: The focus() method is set to the input tag when user clicks on Focus button.


1 Answers

The correct event is onBlur. Look at this code:

<!DOCTYPE html>
<html>
  <head>
    <title>element</title>
<script type="text/javascript">
  function message() {
            var text = document.getElementById("test").value;
            alert(text);
    }
</script>
  </head>
  <body>
      <input type="text" name="test" id="test">
<script type="text/javascript">
document.getElementById("test").onblur=message;
</script>
  </body>
</html>

It works and prints the content of the input when it loses focus. Maybe your error is that you attached the event to the div and not to the input?

like image 143
user4035 Avatar answered Oct 08 '22 19:10

user4035