1

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);
6
  • 1
    Does the element with id "user-text" exist? Does the element with id "submit" exist? Does this run before the user has entered something? Does running this code summon badgers in the next room? What exactly doesn't work here? Commented Feb 18, 2022 at 11:37
  • Most likely you're attaching a click event to the submitter element, and the form is submitted (and the page is reloaded). Set the console to preserve old logs, then you'll see the logged value. That's probably an empty string, though, you've to read the value in the event handler, it's just a string, it's not linked to the value of the element. Commented Feb 18, 2022 at 11:39
  • yes both elements with those ids exist. Commented Feb 18, 2022 at 11:40
  • how do i tell the console to preserve old logs and by the way it worked for me before, i just dont know what i did wrong this time :( Commented Feb 18, 2022 at 11:41
  • i put the userTextValue declaration inside the event handler, still same result. Commented Feb 18, 2022 at 11:44

2 Answers 2

3

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>

Sign up to request clarification or add additional context in comments.

Comments

0

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

3 Comments

@Falconcode Yup, except the form is not submitted to your server (not sure if that even should, though).
i am just experimenting for now, i am taking a React course so just wanted to know how some things worked.
hey it is me again, i have noticed the console holds on to the old values and i want to only show the the input value i submitted on the console. any idea, how can i solve that?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.