0

I want to get the value of an input type number and put it into a global variable. But in the console I get undefined. I need to use the value in other functions. How can I do that?

const bet = document.querySelector('#bet');
let Inputvalue;
bet.addEventListener('change', checkBet)

function checkBet(e) {
  Inputvalue = e.target.value;
}
console.log(Inputvalue)
<input type="number" id="bet" value="" name="bet">
j08691
  • 204,283
  • 31
  • 260
  • 272
yaws76
  • 67
  • 7
  • 2
    How do you expect the console to log a value set when you change an input, before you change the input? – Heretic Monkey Jun 11 '20 at 17:18
  • 2
    Try moving your console.log(Inputvalue); into the checkBet() function – edjm Jun 11 '20 at 17:19
  • 2
    Does this answer your question? [Do let statements create properties on the global object?](https://stackoverflow.com/questions/28776079/do-let-statements-create-properties-on-the-global-object) – agrm Jun 11 '20 at 17:20

2 Answers2

2

The checkBet() function will only be called after you change the value in the input. However, console.log() gets called right away, just as the JS parser reads the file. Since you've not assigned any value to the variable, you will get undefined.

You should either initialize the variable with a value (like 0), or move the console.log() inside the checkBet() function.

Option 1:

const bet = document.querySelector('#bet');
let Inputvalue;
bet.addEventListener('change', checkBet)

function checkBet(e) {
  Inputvalue = e.target.value;
  console.log(Inputvalue)
}

Option 2:

const bet = document.querySelector('#bet');
let Inputvalue = 0;
bet.addEventListener('change', checkBet)

function checkBet(e) {
  Inputvalue = e.target.value;
}
console.log(Inputvalue)
Iscle
  • 679
  • 7
  • 16
  • but like this the InputValue variable will store the value of the input? and i can use it in other part of the code? – yaws76 Jun 11 '20 at 17:27
  • Yes, it will be stored in the global variable. You can try changing the value of the input box and then printing the variable with the Chrome console. – Iscle Jun 11 '20 at 17:35
1

Try this.

const bet = document.querySelector('#bet');
let Inputvalue;
bet.addEventListener('change', checkBet);

function checkBet(e) {
   Inputvalue = e.target.value;
   console.log(Inputvalue)   
}
<input type="number" id="bet" name="bet"/>

Hope this helps

Ashik Paul
  • 486
  • 4
  • 20