Displaying the sum of two Javascript Functions - javascript

The output in the result field is showing NaN for the grandTotal function in the following JavaScript and HTML codes. Please assist to identify the error.
function firstSum(){
subPay=()=>{
let comPay = document.getElementById('totPay').value;
if (comPay > 215000){return (comPay - 215000)*0.25;}
else {return comPay*0.15;}
}
document.getElementById('result1').value = subPay();
}
groPay=()=>{
groEstimate=()=>{
let comPay = document.getElementById('totPay').value;
if (comPay > 220000){return (comPay - 220000)*0.33;}
else {return comPay*0.16;}
}
document.getElementById('result2').value = groEstimate();
}
function grandTotal(){
var allPay;
allPay = firstSum() + groPay();
document.getElementById('result').value = allPay;
}
<form>
<input id="totPay" type="number" placeholder = "groPymt">
<input type = "button" onclick = "grandTotal()" value = "Submit">
<div><input type="text" class="totsum" id="result1"></div>
<div><input type="text" class="totsum" id="result2"></div>
<div>Result: <input type="text" id="result"></div><br><br>
</form>

You should either return the values at the end of firstSum and groPay or change grandTotal to something like
function grandTotal(){
firstSum(); groPay();
const fs = document.getElementById('result1').value;
const gp = document.getElementById('result2').value;
document.getElementById('result').value = fs + gp;
}

Related

Calculate total sum of all the numbers previously entered in a field

i want to calculate the total of the numbers entered by the user. After a user has added item name and the amount, i want to display the total. How can i do this? i just need to display the total.
For example
item name : 10
item name : 5
total = 15
http://jsfiddle.net/81t6auhd/
<body>
<header>
<h1>Exercise 5-2</h1>
</header>
<p>Item: <input type="text" id="item" size="30">
<p>Amount: <input type="text" id="amount" size="30">
<p><span id="message">*</span>
<p><input type="button" id="addbutton" value="Add Item" onClick="processInfo();">
<script>
var $ = function(id) {
return document.getElementById(id);
};
var myTransaction = [];
function processInfo ()
{
var myItem = $('item').value;
var myAmount = parseFloat($('amount').value);
var myTotal = myItem + ":" + myAmount;
var myParagraph = $('message');
myParagraph.innerHTML = "";
myTransaction.push(myTotal);
myParagraph.innerHTML += myTransaction.join("<br>");
};
(function () {
$("addbutton").onclick = processInfo;
})();
</script>
</body>
you have to stored the previous value somewhere in memory to be able to reuse it at next iteration
one proposal can be to stored it in dataset of the field
if ($('amount').dataset.previous) {
myAmount += parseFloat($('amount').dataset.previous);
}
$('amount').dataset.previous = myAmount
var $ = function(id) {
return document.getElementById(id);
};
var myTransaction = [];
function processInfo ()
{
var myItem = $('item').value;
var myAmount = parseFloat($('amount').value);
if ($('amount').dataset.previous) {
myAmount += parseFloat($('amount').dataset.previous);
}
$('amount').dataset.previous = myAmount;
var myTotal = myItem + ":" + myAmount;
var myParagraph = $('message');
myParagraph.innerHTML = "";
myTransaction.push(myTotal);
myParagraph.innerHTML += myTransaction.join("<br>");
};
(function () {
$("addbutton").onclick = processInfo;
})();
<p>Item: <input type="text" id="item" size="30">
<p>Amount: <input type="text" id="amount" size="30">
<p><span id="message">*</span>
<p><input type="button" id="addbutton" value="Add Item" onClick="processInfo();">

adding new value to variable

I have a question I have simple JavaScript that do some basic stuff to a number from input. I have a question how can I make variable that will always track the new input value for example if I enter 123 and click on some of the following buttons I get the result, but if I now enter new number for example 54321 and click again on some of the buttons I start from the previous value. How can I make my variable change every time a new value is entered or changed ? Here is my code:
var number = document.getElementById("number");
var numberValue = number.value;
console.log(numberValue);
function plus() {
number.value = ++numberValue;
}
function minus() {
number.value = --numberValue;
}
function flip() {
var temp = numberValue;
var cifra, prevrten = 0;
while (temp > 0) {
cifra = temp % 10;
prevrten = (prevrten * 10) + cifra;
temp = temp / 10 | 0;
}
number.value = prevrten;
}
window.onload = function() {
number.value = "";
}
<div>
<input type="text" id="number" id="output" onload="restart();">
<input type="button" value="<" onclick="minus();">
<input type="button" value=">" onclick="plus();">
<input type="button" value="FLIP" onclick="flip();">
<input type="button" value="STORE" onclick="store();">
<input type="button" value="CHECK" onclick="check();">
</div>
I suggest you use a type="number" and case the value to number - her I use the unary plus to do so
You will need to read the value in all functions
let numberValue = 0;
function store() {}
function check() {}
function plus() {
numberValue = +number.value;
number.value = ++numberValue;
}
function minus() {
numberValue = +number.value;
number.value = --numberValue;
}
function flip() {
let numberValue = +number.value;
var cifra, prevrten = 0;
while (numberValue > 0) {
cifra = numberValue % 10;
prevrten = (prevrten * 10) + cifra;
numberValue = numberValue / 10 | 0;
}
number.value = prevrten;
}
window.addEventListener("load", function() {
let number = document.getElementById("number");
number.value = 0;
})
<div>
<input type="number" id="number" id="output" onload="restart();">
<input type="button" value="<" onclick="minus();">
<input type="button" value=">" onclick="plus();">
<input type="button" value="FLIP" onclick="flip();">
<input type="button" value="STORE" onclick="store();">
<input type="button" value="CHECK" onclick="check();">
</div>
Try using onChange="".
<input type="text" id="number" id="output" onload="restart();" onChange="updateVal();">
function updateVal() {
numberValue = number.value;
}
I would suggest, for something like this, it would be much easier to use React JS or another framework with state.

trying to link checkbox list with multiple functions using HTML & JAVASCRIPT

my code calculates the AVG or MAX of an input set of numbers, I want the user to check on a checkbox list that contains AVG and MAX for desired output but I couldn't figure out doing it.
if I put an input of "2,4" without check listing the output is both AVG and MAX which is 3 4, I tried to checklist for only AVG or MAX outcome but it didn't work.
I have checked both function calculateAVG() & calculateMAX() and they produce correct output
function proccesFloat(flt) {
var splitFloat = flt.split(",");
for (x in splitFloat) {
splitFloat[x] = parseFloat(splitFloat[x]);
}
return splitFloat;
}
function calculateAVG(setNum) {
let total = 0;
var numInput = document.getElementById("setNum").value;
var result = 0;
var avg = proccesFloat(numInput);
for (let i = 0; i < avg.length; i++) {
total += avg[i];
}
result = total / avg.length;
document.getElementById('outputAVG').innerHTML = result;
}
function calculateMAX(setNum) {
var numInput = document.getElementById("setNum").value;
var numarry = proccesFloat(numInput);
var max = 0;
for (let i = 0; i < numarry.length; i++) {
if (numarry[i] > max) {
max = numarry[i];
}
}
document.getElementById('outputMAX').innerHTML = max;
}
function calculate() {
var checkBox = document.getElementsByTagName("check");
if (checkBox[0].checked) {
calculateAVG(document.getElementById("setNum"));
}
if (checkBox[0].checked) {
calculateMAX(document.getElementById("setNum"));
} {
alert('please choose formula')
return false;
}
}
<header>
<input type="Numbers" id="setNum" placeholder="Enter Set of Numbers">
<br>
<button onclick="calculate()" id="btn1">calculate</button>
<output id="outputAVG"></output>
<output id="outputMAX"></output>
<form method="post">
<fieldset>
<legend>Formula To Calculate?</legend>
<input type="checkbox" id="avg" name="check" onclick="calculate()">AVG<br>
<input type="checkbox" id="max" name="check" onclick="calculate()">MAX<br>
<br>
</fieldset>
</form>
</header>
Count the checked and then look at the IDs.
I also suggest you wrap in a form and use the submit event
I made a few more changes to simplify the code
Let the functions do one thing and use the event to bring them together
const proccesFloat = flt => flt.split(",").map(fl => +fl); // cast to float
const calculateAVG = setNum => {
const arr = proccesFloat(setNum);
const total = arr.reduce((a, b) => a + b)
return total / arr.length;
}
const calculateMAX = setNum => Math.max(...proccesFloat(setNum));
document.getElementById("calcForm").addEventListener("submit", function(e) {
e.preventDefault(); // stop submission
const chks = document.querySelectorAll("[name=check]:checked")
if (chks.length === 0) {
alert('please choose formula')
return
}
if (document.getElementById("avg").checked) {
document.getElementById('outputAVG').innerHTML = calculateAVG(document.getElementById("setNum").value);
}
if (document.getElementById("max").checked) {
document.getElementById('outputMAX').innerHTML = calculateMAX(document.getElementById("setNum").value);
}
})
<header>
<form id="calcForm">
<input type="Numbers" id="setNum" placeholder="Enter Set of Numbers">
<br>
<button type="submit">calculate</button>
<output id="outputAVG"></output>
<output id="outputMAX"></output>
<fieldset>
<legend>Formula To Calculate?</legend>
<input type="checkbox" id="avg" name="check">AVG<br>
<input type="checkbox" id="max" name="check">MAX<br>
<br>
</fieldset>
</form>
</header>

Adding 2 input values on keyup to get the answer in the 3rd input box

i know this has been asked before but i can't seem to get this right. I need to take input values from two text boxes and add it to another and that answer should appear in the 3rd textbox after both boxes are typed in. Nothing seems to be happening however though. Thanks
Here's the HTML
//Input 1
<input name="attribute_campaign_addon_one_time_cost_value" id="am_attribute_campaign_addon_one_time_cost_value">
//Input 2
<input name="attribute_campaign_addon_total_monthly_cost_value" id="attribute_campaign_addon_total_monthly_cost_value">
//Input 3 where added answer should go
<input name="attribute_campaign_addon_total_monthly_cost_calculated_value" id="am_attribute_campaign_addon_total_monthly_cost_calculated_value" value="">
//JQ
var $oneTimeCostField = $('#am_attribute_campaign_addon_one_time_cost_value');
var $recurringTotalCostField = $('#am_attribute_campaign_addon_total_monthly_cost_value');
var $totalRetailAmountField = $('#am_attribute_campaign_addon_total_monthly_cost_calculated_value');
function calcVal() {
var num1 = $oneTimeCostField.val();
var num2 = $recurringTotalCostField.val();
var result = parseInt(num1) + parseInt(num2);
if (!isNaN(result)) {
$totalRetailAmountField.val() = result;
}
}
calcVal();
$(num1, num2).on("keydown keyup", function() {
calcVal();
});
Your selector for the onkeyup/down is wrong, and your total field has the wrong id.
The result can be set like this: $totalRetailAmountField.val(result);
//JQ
var $oneTimeCostField = $('#am_attribute_campaign_addon_one_time_cost_value');
var $recurringTotalCostField = $('#am_attribute_campaign_addon_total_monthly_cost_value');
var $totalRetailAmountField = $('#am_attribute_campaign_addon_total_monthly_cost_calculated_value');
function calcVal() {
var num1 = $oneTimeCostField.val();
var num2 = $recurringTotalCostField.val();
var result = parseInt(num1, 10) + parseInt(num2, 10);
console.log("calcVal ", num1,num2, result);
if (!isNaN(result)) {
$totalRetailAmountField.val(result);
}
}
calcVal();
$oneTimeCostField.on("keydown keyup", function() {
calcVal();
});
$recurringTotalCostField.on("keydown keyup", function() {
calcVal();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
//Input 1
<input name="attribute_campaign_addon_one_time_cost_value" id="am_attribute_campaign_addon_one_time_cost_value">
//Input 2
<input name="attribute_campaign_addon_total_monthly_cost_value" id="am_attribute_campaign_addon_total_monthly_cost_value">
//Input 3 where added answer should go
<input name="attribute_campaign_addon_total_monthly_cost_calculated_value" id="am_attribute_campaign_addon_total_monthly_cost_calculated_value" value="">
http://api.jquery.com/val/
Jquery input value is set as follows:
$totalRetailAmountField.val(result);
First thing, I have never seen name & id such big value. this is not only cause problem in readability but also introduce error like unwanted space in id
Secondly num1 & num2 are already jquery object then what is the use of $(num1, num2)
Thirdly update the value of the third input by passing the vale as function argument $totalRetailAmountField.val(result);
var $oneTimeCostField = $('#am_attribute_campaign_addon_one_time_cost_value');
var $recurringTotalCostField = $('#attribute_campaign_addon_total_monthly_cost_value');
var $totalRetailAmountField = $('#am_attribute_campaign_addon_total_monthly_cost_calculated_value');
function calcVal() {
var num1 = $oneTimeCostField.val();
var num2 = $recurringTotalCostField.val();
var result = parseInt(num1) + parseInt(num2);
if (!isNaN(result)) {
$totalRetailAmountField.val(result);
}
}
$('#attribute_campaign_addon_total_monthly_cost_value,#am_attribute_campaign_addon_one_time_cost_value').on("keydown keyup", function() {
calcVal();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="attribute_campaign_addon_one_time_cost_value" id="am_attribute_campaign_addon_one_time_cost_value">
<input name="attribute_campaign_addon_total_monthly_cost_value" id="attribute_campaign_addon_total_monthly_cost_value">
<input name="attribute_campaign_addon_total_monthly_cost_calculated_value" id="am_attribute_campaign_addon_total_monthly_cost_calculated_value" value=" ">
This is a fairly verbose solution to your query.
Listen to change on each input and apply their respective values to the final answer input (input#fa)
const a1 = document.querySelector('#a1')
const a2 = document.querySelector('#a2')
const fa = document.querySelector('#fa')
const answers = []
const _handleFinalAnswer = () => (fa.value = (+answers[0] || 0) + (+answers[1] || 0))
a1.addEventListener('change', e => {
const { value } = e.target
answers[0] = value
_handleFinalAnswer()
})
a2.addEventListener('change', e => {
const { value } = e.target
answers[1] = value
_handleFinalAnswer()
})
<input type="number" step="any" name="answer 1" id="a1" />
<input type="number" step="any" name="answer 2" id="a2" />
<input name="final answer" id="fa" />
Or here is a more dynamic way to calculate all possible amount of inputs to achieve a final sum but it could still be done with two inputs :-)
const answersInputs = document.querySelectorAll('input.answer')
const finalAnswer = document.querySelector('#fa')
const _getSummedValues = () => (
[...answersInputs]
.map(input => +input.value || 0)
.reduce((prev, curr) => prev+curr, 0)
)
const _setFinal = () => finalAnswer.value = _getSummedValues()
answersInputs.forEach(input => input.addEventListener('change', _setFinal))
<input type="number" step="any" name="answer 1" class="answer" />
<input type="number" step="any" name="answer 2" class="answer" />
<input type="number" step="any" name="answer 3" class="answer" />
<input type="number" step="any" name="answer 4" class="answer" />
<input type="number" step="any" name="answer 5" class="answer" />
<input type="number" step="any" name="answer 6" class="answer" />
<input type="number" step="any" name="answer 7" class="answer" />
<input name="final answer" id="fa" />

Add 2 functions

I'm trying to add my getExamGrades and getLabGrades together by calling my other function to get a total grade but nothing I've tried works. Everything I've done so far just eliminates both of the functions I call and leaves everything blank. The code below works perfectly fine, just need help with the last part and then I can figure out the other variables and functions.
<!DOCTYPE html>
<html>
<header>
<script>
function getExamGrades()
{
var exam1 = document.getElementById("Exam1").value;
var exam2 = document.getElementById("Exam2").value;
var exam3 = document.getElementById("Exam3").value;
var Exams = Number(exam1) + Number(exam2) + Number(exam3);
document.getElementById("examGrade").innerHTML = Exams;
}
function getLabGrades()
{
var lab1 = document.getElementById("Lab1").value;
var lab2 = document.getElementById("Lab2").value;
var lab3 = document.getElementById("Lab3").value;
var Labs = Number(lab1) + Number(lab2) + Number(lab3);
document.getElementById("labGrade").innerHTML = Labs;
}
function getTotalGrades()
{
//var Total = Number(getExamGrades()) + Number(getLabGrades();
document.getElementByID("totalGrade").innerHTML = Total;
}
</script>
</header>
<body>
Exam1: <input type = "text" name="Exam1" value ="100" id="Exam1">
Exam2: <input type = "text" name="Exam2" value ="100" id="Exam2">
Exam3: <input type = "text" name="Exam3" value ="100" id="Exam3">
<br><br>
<button onClick="getExamGrades()"> Calculate Exam Grade </button>
Total: <output id="examGrade"> </output>
<br><br>
Lab1: <input type = "text" name="Lab1" value ="100" id="Lab1">
Lab2: <input type = "text" name="Lab2" value ="100" id="Lab2">
Lab3: <input type = "text" name="Lab3" value ="100" id="Lab3">
<br><br>
<button onClick="getLabGrades()"> Calculate Lab Grade </button>
Total: <output id="labGrade"> </output>
<br><br>
<button onClick="getTotalGrades()"> Calculate Total Grade </button>
Final Grade: <output id="totalGrade"> </output>
</body>
</html>
Your functions are not returning the values. If they did, then what you were trying would work. Try it like this:
function getExamGrades()
{
var exam1 = document.getElementById("Exam1").value;
var exam2 = document.getElementById("Exam2").value;
var exam3 = document.getElementById("Exam3").value;
var Exams = Number(exam1) + Number(exam2) + Number(exam3);
document.getElementById("examGrade").innerHTML = Exams;
return Exams;
}
function getLabGrades()
{
var lab1 = document.getElementById("Lab1").value;
var lab2 = document.getElementById("Lab2").value;
var lab3 = document.getElementById("Lab3").value;
var Labs = Number(lab1) + Number(lab2) + Number(lab3);
document.getElementById("labGrade").innerHTML = Labs;
return Labs;
}
function getTotalGrades()
{
var Total = Number(getExamGrades()) + Number(getLabGrades());
document.getElementById("totalGrade").innerHTML = Total;
}
There were a couple of other minor issues that I fixed for you too.
You can see a working example here: http://jsfiddle.net/8js5uewc/2/

Categories