How to get data from the html input after the user has pressed enter or clicked elsewhere?

Js has a built-in function that allows you to retrieve data from an input when a user enters something into it: input.addEventListener("input", myFunction()).
But it does not suit me, because it is executed every time the user enters at least one character. Instead, I need an approach in which the function would be called only when the user typed something and then pressed enter or clicked on a page in different place.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can use the following methods for this:

  1. use onblur for the input elements. This will trigger once the user clicks anywhere outside of that input box.
  2. use onsubmit for the form. This will trigger when the user presses enter or submits the form in anyway.

Method 2

You can use the focusout event which fires when an element is about to lose focus and for the enter key you could check the event.key within the keypress event which is fired when a key that produces a character value is pressed down. like so:

input.addEventListener("keypress", function (e) {
   if (e.key === 'Enter') {
     // code for enter
   }
});

focusouthttps://developer.mozilla.org/en-US/docs/Web/API/Element/focusout_event

keypresshttps://developer.mozilla.org/en-US/docs/Web/API/Document/keypress_event


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x