Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

125
Views
assign the value of `input ` to a variable but return blank in JS

I want to assign the value of input to a variable in Javascript, but I am not sure why the value of input is always blank.

Here is an example:

let input = document.getElementById('input').value
let val = 'not'

function check() {
  //console.log(document.getElementById('input').value) will work
  console.log(typeof input)
  console.log(input)

}
<input id='input' type='text'>
<button onclick='check()'>Check</button>

The input value is blank (nothing), but the typeof input is string.

If I use document.getElementById('input').value, this will totally work which will display the value of input sucessfully.

Could anyone explain me a little bit why I assign it to a variable won't work?

Thanks for any responds!

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

Variable assignment val = 'not' takes place at the first time page load. When you need to assign dynamic value, like on a button click, you need an event handling mechanism (In your case, a click event). You are calling a function upon click, but not assigning any value to your variable there. Make assignment inside function like:

function check() {
  val = document.getElementById('input').value
  console.log(val)
}
about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!