1

In the below code, I am trying to console.log the form input value when a button gets clicked. However, upon the button click, the value is only getting logged momentarily before disappearing. why is this happening and how to resolve it?

document.querySelector("button").addEventListener("click",function(){
  const listItem = document.querySelector("input").value;
  console.log(listItem);
});
<body>  
  <form action="">
    <input type="text">
    <button class ="btn btn-lg btn-primary" type="submit"> ADD </button>
  </form>
</body>
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Reniya Naji
  • 81
  • 1
  • 1
  • 4
  • 1
    Does this answer your question? [Stop form refreshing page on submit](https://stackoverflow.com/questions/19454310/stop-form-refreshing-page-on-submit) – theusaf Jul 26 '20 at 02:34
  • 2
    You submit your form upon clicking. Thus, it disappears. Change the button type from submit to button – j08691 Jul 26 '20 at 02:40

3 Answers3

4

When submitting a form, the browser sends a request to the server and refreshes the page. To disable this behavior, you can use event.preventDefault() when clicking the button

document.querySelector("button").addEventListener("click",function(event){
  event.preventDefault();
  const listItem = document.querySelector("input").value;
  console.log(listItem);
});
<body>  
  <form action="">
    <input type="text">
    <button class ="btn btn-lg btn-primary" type="submit"> ADD </button>
  </form>
</body>
theusaf
  • 1,781
  • 1
  • 9
  • 19
0

Others have explained that submitting a form reloads the page. But that doesn't really address the question about the console log.

Go to the Developer Tools settings, and in the Console section check Preserve log upon navigation. Then you won't lose log messages when the page reloads because of the form submission.

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

This is because browser reloads on the form submission. And your data is lost. To prevent this simply use "event.preventDefault()" function after your log statement after passing "event" as a parameter in the event listener function. Like this:

document.querySelector("button").addEventListener("click", function (event) { const listItem = document.querySelector("input").value;
console.log(listItem); event.preventDefault(); });