Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

50
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!

7 months 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)
}
7 months ago · Santiago Gelvez Report
Answer question
Find remote jobs