0

I am working with html forms and adding functionality to buttons using JS. I have created a to capture the user's name once this ones is introduced in the text field. The problem is that when I try to display the user's input on the console, this one appears for a very short instant and then disappears. `

The following is my HTML code:

    <form action="">
        <div>
            <label for="myName">Name</label>
        </div>
        <div>
            <input type="text" name="myName" id="myName" class="name">
        </div>
            <button class="thisOne">Collect Info</button>

    </form>`

The next one is my JS

` let input_name = document.querySelector('.name');
     let btn = document.querySelector('button');
     btn.addEventListener('click', ()=>{   
     console.log(input_name.value);
      });`
  • ` – Carsten Massmann Apr 06 '22 at 18:49
  • Set your button type to "button". I know it sounds redundant but gives you a button with no actions attached to it (such as submit). – Phaelax z Apr 06 '22 at 18:52
  • Phaelax z, you mean adding a I wasn't aware that – Alexander Martinez Apr 06 '22 at 18:56

1 Answers1

1

Use event, and preventDefault, to prevent sending the form.

const input_name = document.querySelector('.name');

const btn = document.querySelector('.thisOne');

btn.addEventListener('click', (e)=>{
  e.preventDefault();
  console.log(input_name.value);
});
<form action="">
  <div>
      <label for="myName">Name</label>
  </div>
  <div>
      <input type="text" name="myName" id="myName" class="name">
  </div>
      <button class="thisOne">Collect Info</button>
</form>
exphoenee
  • 465
  • 4
  • 11