Issue
How do I correctly perform calculations from two text inputs? I don't seem to know what I am doing wrong here. I am trying to pull data from my HTML code by trying to multiply two values from two input text boxes that the user would put.
The result will display in another input text box once the calculate button is pressed and the action is performed.
However, If I type in two numbers in each box, no result will appear. Why is this and how might I fix it?
Thank you.
**JavaScript**
function calcStepDays(st, dw) {
var tsw = (st * dw);
return tsw;
}
function clickCalc( ) {
var st = parseFloat(
document.getElementById("stepsTaken").value);
var dw = parseFloat(
document.getElementById("daysWalked").value);
var tsw = calcStepDays(st, dw);
var result = document.getElementById("totalWalks");
var roundRus = Math.round(tsw * 100) / 100;
result.value = roundRus.valueOf( );
}
function init( ) {
var button = document.getElementById("button1");
button.addEventListener("click", clickCalc);
}
window.addEventListener = ("load", init);
**HTML**
<p>Input the number of steps you believe you've taken today and how many days you've walked to see your total steps</p>
<label for="stepsTaken"> Average steps walked per day</label><br><br>
<input type="text" id="stepsTaken"><br><br>
<label for="daysWalked"> Amount of days walked</label><br><br>
<input type="text" id="daysWalked"><br><br>
<button id="button1">
Calculate</button><br><br>
<label for="totalWalks">Total Steps</label>
<input type="text" id="totalWalks"><br><br>
Solution
You have a typo when adding the event listener on Window. Since the init() function was never called. The button never was assigned the function. It should be:
window.addEventListener("load", init);
Added a working solution:
function calcStepDays(st, dw) {
var tsw = (st * dw);
return tsw;
}
function clickCalc( ) {
var st = parseFloat(
document.getElementById("stepsTaken").value);
var dw = parseFloat(
document.getElementById("daysWalked").value);
var tsw = calcStepDays(st, dw);
var result = document.getElementById("totalWalks");
var roundRus = Math.round(tsw * 100) / 100;
result.value = roundRus.valueOf( );
}
function init( ) {
var button = document.getElementById("button1");
button.addEventListener("click", clickCalc);
}
window.addEventListener("load", init);
<p>Input the number of steps you believe you've taken today and how many days you've walked to see your total steps</p>
<label for="stepsTaken"> Average steps walked per day</label><br><br>
<input type="text" id="stepsTaken"><br><br>
<label for="daysWalked"> Amount of days walked</label><br><br>
<input type="text" id="daysWalked"><br><br>
<button id="button1">
Calculate</button><br><br>
<label for="totalWalks">Total Steps</label>
<input type="text" id="totalWalks"><br><br>
Answered By - Jae
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.