Home > other >  I cant get an Input value with javascript
I cant get an Input value with javascript

Time:02-19

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

CodePudding user response:

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>

CodePudding user response:

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

CodePudding user response:

The function must have a defined parameter.

It's better to set the userTextValue variable without .value, you will declare it when calling the show() function.

const userTextValue = document.getElementById('user-text');
const submit = document.getElementById('submit');

submit.addEventListener('click', () => {
    show(userTextValue.value);
});

const show = (value) => {
  console.log(value);
};
<input type="text" id="user-text">
<input type="submit" id="submit">

I hope helped you!

  • Related