Reputation: 27
So i am trying to get the value of an input tag with javascript and show it on the console but it doesnot work at all. this is my code, what am i missing here?
const userTextValue = document.getElementById('user-text').value;
const show = () => {
console.log(userTextValue);
}
const submit = document.getElementById('submit');
submit.addEventListener('click', show);
Upvotes: 1
Views: 149
Reputation: 446
when you submit the page refresh by default to prevent that you can do it like this
const show = (e) =>{
e.preventDefault();
console.log(userTextValue);
}
Upvotes: 0
Reputation: 3157
Access the input value when you click on show button, so that you get the updated value entered by user.
const show = () => {
const userTextValue = document.getElementById('user-text').value;
console.log(userTextValue);
}
const submit = document.getElementById('submit');
submit.addEventListener('click', show);
<div>
<input id="user-text" />
<button id="submit">Show</button>
</div>
Upvotes: 3