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" >
</div>
<button >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);
});`
CodePudding user response:
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" >
</div>
<button >Collect Info</button>
</form>