Samuel666
Samuel666

Reputation: 11

Global variable declaration returns undefined, any reason for this

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>`

Upvotes: 1

Views: 48

Answers (2)

Glenn Ferrie
Glenn Ferrie

Reputation: 10400

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 class="listBox">
        <option value="a"> Option A </option>
        <option value="b"> Option B </option>
        <option value="c"> Option C </option>
    </select>
    <input type="text" class="addtext" />  
    <button class="addButton"> 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

Upvotes: 0

Mr_NAIF
Mr_NAIF

Reputation: 136

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

Upvotes: 2

Related Questions