Why Is My JavaScript Add Function Always Returning Zero?

0
10
Asked By SunnySideUp42 On

I'm new to JavaScript and I'm trying to create a simple addition feature using input fields and a button. However, whenever I click the button, it always outputs zero. Here's a quick look at my code:

result

And my script:

var box1 = document.getElementById("num1").value;
var box2 = document.getElementById("num2").value;
var result = document.getElementById("result");

function resultfunction() {
var box2value = Number(box1);
var box1value = Number(box2);
var total = box1value + box2value;
result.textContent = total;
}

I've noticed that the values are saved at the beginning, which might be causing issues. Can someone help me figure out what's going wrong?

2 Answers

Answered By TechGuru432 On

You might want to directly reference the input elements in your `resultfunction()` instead of saving their values outside the function. Code outside of functions only executes once when the page loads, so at that time, those variables are empty. If you change your function to grab the values when it's executed, it should give the correct result! Here's how you could tweak it:

function resultfunction() {
var box1 = document.getElementById("num1").value;
var box2 = document.getElementById("num2").value;
var box1value = Number(box1);
var box2value = Number(box2);
var total = box1value + box2value;
result.textContent = total;
}

SunnySideUp42 -

Got it! That makes sense now. Thanks for clarifying!

Answered By CodingWhiz101 On

The issue here is that you're grabbing the values from the input fields too early. When your script runs at the top, it gets the values immediately after the page loads, which means they are still empty at that moment. Instead, you should fetch the values inside your `resultfunction()` whenever you click the button. Here's a better way to structure it:

function resultfunction() {
var box1 = document.getElementById("num1").value;
var box2 = document.getElementById("num2").value;
var box1value = Number(box1);
var box2value = Number(box2);
var total = box1value + box2value;
result.textContent = total;
}

By doing this, you're ensuring you get the current values of the inputs when the button is clicked. Also, don't worry too much about mixing up variable names; it happens to the best of us!

CuriousCoder99 -

Oh, thank you! But I'm still a bit confused. If I'm entering values into the inputs, why doesn't it work when I click 'Add'? I don't really understand what you mean by "grabbing input values too early." I saw someone on YouTube do it this way and it worked for them.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.