I am very new to Javascript and am looking for a solution to better understand how this works.
I am making a simple budget app with various user text inputs. What I want to accomplish is to store these user inputs inside variables within JS, have them added, possibly compared, then return a total on the page when the user clicks a button in the empty paragraph element. Here is a sample of the html code (I have only included two of the inputs as they will work the same and just need an understanding of the concept):
<ul>
<li><p>Money In:</p></li>
<br>
<li class="inputHeading">Current Balance</li>
<li><input type="text" class="input" id="balanceInput"></li>
<li><p>Money Out:</p></li>
<br>
<li class="inputHeading">Rent</li>
<li><input type="text" class="input" id="rentInput"></li>
<li><input type="button" class="button" value="AMOUNT LEFT" onclick="calcTotal()"></li>
<li class="output" id="amountOutput"><p></p></li>
</ul>
I have researched various methods but most of what I find is far more complex than I can currently understand. I wanted to see if anyone could both suggest and explain a solution to how to do this. Your help would be much appreciated!
You can store the input in js with document.getElementById("id").value
However this will be stored in string, so you need to change it into integer/float if you want to calculate the total
parseFloat() is the method to parse string text into float values.
In the example you provided, the values is current balance and rent, hence I think it is more suitable to find the difference instead of adding them together.
function calcTotal() {
var inputbal = parseFloat(document.getElementById("balanceInput").value);
var inputrent = parseFloat(document.getElementById("rentInput").value);
var balance = inputbal - inputrent;
document.getElementById("balance").innerHTML = balance.toFixed(2);
}
<ul>
<li>
<p>Money In:</p>
</li>
<br>
<li class="inputHeading">Current Balance</li>
<li><input type="text" class="input" id="balanceInput"></li>
<li>
<p>Money Out:</p>
</li>
<br>
<li class="inputHeading">Rent</li>
<li><input type="text" class="input" id="rentInput"></li>
<li><input type="button" class="button" value="AMOUNT LEFT" onclick="calcTotal()"></li>
<li class="output" id="amountOutput">
<p></p>
</li>
</ul>
<p id="balance"></p>