Home > Blockchain >  Global variable declaration returns undefined, any reason for this
Global variable declaration returns undefined, any reason for this

Time:01-25

When I log input to the console, it returns undefined but when put inside a the anonymous function, it logs to the console as expected

I had tried the below code, and expected that the inputValue to be logged to the console on click of the addButton, however, the value from inputValue when logged was undefined, the value of inputValue is meant to be gotten from an inputbox.

`

const addButton=document.querySelector(".addButton");
let listBox=document.querySelector(".listBox");
let input=document.querySelector(".addtext").value;
let inputValue=input;
addButton.addEventListener('click',()=>{
console.log(inputValue)});

</script>
</body>
</html>`

CodePudding user response:

Maybe because this line of code captures the value before it get changed:

let input=document.querySelector(".addtext").value;

Try this:

const addButton=document.querySelector(".addButton");
let listBox=document.querySelector(".listBox");
let input=document.querySelector(".addtext");
addButton.addEventListener('click',()=>{
console.log(input.value)});

CodePudding user response:

Here is some code that I created based on your sample. I've also included a codepen for demo.

the keyword let isn't hoisted and it is limited in scope. variables defined with var are hoisted, meaning they are brought to the top of the script and executed first when the JS file is processed by the browser.

Here is my code, I made all of the variable targeting the controls as const.

Then I reference the value property in the event handler.

<div>
    <select >
        <option value="a"> Option A </option>
        <option value="b"> Option B </option>
        <option value="c"> Option C </option>
    </select>
    <input type="text"  />  
    <button > Add </button>
</div>

This is the JS Code:

const addButton=document.querySelector(".addButton");
const listBox=document.querySelector(".listBox");
const input=document.querySelector(".addtext");
addButton.addEventListener('click',() => {
  console.log(input.value)
});

https://codepen.io/glennferrie/pen/gOjeQNx

  • Related