Home > database >  assign the value of `input ` to a variable but return blank in JS
assign the value of `input ` to a variable but return blank in JS

Time:12-11

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!

CodePudding user response:

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)
}
  • Related