简体   繁体   中英

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM