1

For some reason the variables set in my functions only apply to the scope of the function, even with window in front of the declaration:

<body>
<input id="usernameBox" placeholder="Name">
<input id="ageBox" placeholder="Age">
<br>
<button onclick="changeUsername(), changeAge()"id="niceButton">Confirm</button>
<script>
    var username;
    var age;
    function changeUsername(){
        window.username=document.getElementById("usernameBox").value
        console.log(username)
    }
    function changeAge(){
        window.age=document.getElementById("ageBox").value
        console.log(age)
    }
    console.log(username);
</script>

The final console log is supposed to log what's inserted in the text box "usernameBox", but it just prints undefined, even after the button is clicked. I even added a checker within the functions, and they properly log what's inside the text boxes when clicked, so why is username still undefined outside of the function?

Candog85
  • 13
  • 3
  • You have 2 variables declared at the top of your document without any assigned value (they are undefined at the time of your console log). When the page loads, the file is evaluated and the console log runs before you have set values with your onclick handler, essentially that console log at the very end prints the unaltered variabled `username` and `age` just as you've declared them. If you were to set a default value for username for example like `var username = 'bob'` you would see the output of `bob` and then it would print whatever else you set in your functions onclick. – Vladimir Mujakovic Jun 23 '21 at 00:49

3 Answers3

1

Your issue is that the <script> tag gets called at the very beginning of the process. So you are logging it before it is even set.
Try making a function that prints out both values such as:

function LogStuff(){
    console.log(username, age);
}

And call it after the events such as:

<button onclick="changeUsername(); changeAge(); LogStuff();"id="niceButton">Confirm</button>

The reason why it was working in the functions is because you were setting the global variables locally before using them, so it was no longer undefined

Gunnarhawk
  • 437
  • 3
  • 12
  • Thanks, so if I were to add a line such as ```document.write(`Hello, ${username}!`)``` would I have to make it a function and add it to things to do onclick? – Candog85 Jun 23 '21 at 00:36
  • Add a new element to the HTML and then grab the element like in my example and then ``element.textContent = `Hello, ${username}``. There's some answers for not using `document.write` [here](https://stackoverflow.com/questions/4537963/what-are-alternatives-to-document-write). – Andy Jun 23 '21 at 01:40
1
  1. The script runs before you click the button, and username will always be undefined at that point.

  2. You shouldn't really need global variables. If this is a form to be submitted you can handle it within the handleClick function, or ask handleClick to call another function with the input values.

  3. I'd recommend removing the inline JavaScript too so you can manage it better.

// Cache your elements
const usernameBox = document.querySelector('#usernameBox');
const ageBox = document.querySelector('#ageBox');
const button = document.querySelector('button');

// Add a click listener that runs the `handleClick` function
button.addEventListener('click', handleClick, false);

// Grab the values of the boxes and log them
function handleClick() {
  console.log(usernameBox.value, ageBox.value);      
}
<input id="usernameBox" placeholder="Name">
<input id="ageBox" placeholder="Age">
<br>
<button>Confirm</button>
Andy
  • 61,948
  • 13
  • 68
  • 95
  • Okay, thanks, just one question, what is the purpose of ```true``` at the end of the event listener? How does it complete the line? – Candog85 Jun 23 '21 at 01:20
  • It's all in [the documentation](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) – Andy Jun 23 '21 at 01:28
0

ya already call console.log(username) with a value

you can do like this

var username = ''; var age = '';

or just remove the console.log(username) under function changeAge()

changeUsername() and changeAge() will only execute if you clicked the button

JOCKEY
  • 33
  • 6