Reniya Naji
Reniya Naji

Reputation: 91

why is the form value disappearing from the console log?

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>

Upvotes: 1

Views: 2141

Answers (3)

Abhishekh
Abhishekh

Reputation: 1

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(); });

Upvotes: 0

Barmar
Barmar

Reputation: 780869

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.

Upvotes: 0

theusaf
theusaf

Reputation: 1802

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>

Upvotes: 4

Related Questions