Javascript Loop - Adding a var to the while condition? - javascript

Basically I want to count and display the amount of months it would take to get to a certain point (savings balance) based on a contribution every month.
Here is what I have so far:
function howLong(initial,interest,goal,added){
var initialDeposit = parseInt(initial);
var interestInt = parseInt(interest);
var targetSaving = parseInt(goal);
var contribution = parseInt(added);
var monthCount = 0;
while(initialDeposit <= targetSaving){
monthCount++;
initialDeposit+contribution
}
alert(monthCount)
}
Here is my html form:
<form>
Initial Deposit:<br />
<input type="number" id="initial"><br /><br />
Interest:<br />
<input type="number" id="interest"><br /><br />
Target savings amount:<br />
<input type="number" id="goal"><br /><br />
Monthly Contribution:<br />
<input type="number" id="contribution"><br /><br />
<input type="button" value="How Long!?" onclick="howLong(document.getElementById('initial').value,document.getElementById('interest').value,document.getElementById('goal').value),document.getElementById('contribution').value">
</form>

You need to add the value of contribution to initialDeposit.
initialDeposit += contribution;
For the other problem, you have an error in the call of the function
document.getElementById('goal').value),document.getElementById('contribution').value"
^ >>>>>>>>>>>>>>>> should go >>>>>>>>>>>>>>>>> ^
shold be
onclick="howLong(
document.getElementById('initial').value,
document.getElementById('interest').value,
document.getElementById('goal').value,
document.getElementById('contribution').value
)"
The last round bracket is closing to early.
function howLong(initial, interest, goal, added) {
var initialDeposit = parseInt(initial);
var interestInt = parseInt(interest);
var targetSaving = parseInt(goal);
var contribution = parseInt(added);
var monthCount = 0;
while (initialDeposit <= targetSaving) {
monthCount++;
initialDeposit += contribution;
}
alert(monthCount)
}
<form>
Initial Deposit:<br />
<input type="number" id="initial"><br /><br /> Interest:
<br />
<input type="number" id="interest"><br /><br /> Target savings amount:<br />
<input type="number" id="goal"><br /><br /> Monthly Contribution:<br />
<input type="number" id="contribution"><br /><br />
<input type="button" value="How Long!?" onclick="howLong(document.getElementById('initial').value,document.getElementById('interest').value,document.getElementById('goal').value,document.getElementById('contribution').value)">
</form>

Change to initialDeposit += contribution;

As other answers have pointed out initialDeposit += contribution will solve the issue, but you don't need a loop here at all:
var monthCount = Math.ceil((targetSaving - initialDeposit)/contribution);
This is presuming that the contribution is constant, of course.

You were missing += operator and interest as well.
function howLong(){
var initialDeposit = parseInt(document.getElementById('initial').value);
var interestInt = parseInt(document.getElementById('interest').value);
var targetSaving = parseInt(document.getElementById('goal').value);
var contribution = parseInt(document.getElementById('contribution').value);
var monthCount = 0;
while(initialDeposit <= targetSaving){
monthCount++;
initialDeposit += contribution + interestInt; //+= was missing and interestInt as well
}
alert(monthCount);
}
<form>
Initial Deposit:<br />
<input type="number" id="initial"><br /><br />
Interest:<br />
<input type="number" id="interest"><br /><br />
Target savings amount:<br />
<input type="number" id="goal"><br /><br />
Monthly Contribution:<br />
<input type="number" id="contribution"><br /><br />
<input type="button" value="How Long!?" onclick="howLong()">
</form>

Related

Javascript how to sum tables

Hello I have a problem with such a task I totally don't know how to get down to it, I hope someone will help me to write an application allowing to calculate the sum and the difference of two 2-dimensional numerical tables. Each of these tables should have 2 lines and 3 columns. Input data - the values of individual array elements - enter the keypads. Present the results on screen, on the same website.
My code is below:
<!DOCTYPE html>
<html lang="pl">
<head>
<title> JavaScript: tablice 2-wymiarowe. </title>
<meta charset="UTF-8">
</head>
<body>
<form id="form1">
Podaj 12 liczb <br />
Pierwsza: <input id="input1" type="text" value="1" /><br />
Druga: <input id="input2" type="text" value="2" /><br />
Trzecia: <input id="input3" type="text" value="3" /><br />
Czwarta: <input id="input4" type="text" value="4" /><br />
piata: <input id="input5" type="text" value="5" /><br />
szosta: <input id="input6" type="text" value="6" /><br />
</form>
<button onclick="przetwarzanie();"> Oblicz </button>
<div id="div1"> </div>
<script>
function przetwarzanie() {
var input1 = document.getElementById("input1");
var input2 = document.getElementById("input2");
var input3 = document.getElementById("input3");
var input4 = document.getElementById("input4");
var input5 = document.getElementById("input5");
var input6 = document.getElementById("input6");
var div1 = document.getElementById("div1");
var tablica = [];
tablica[0] = Number(input1.value, input2.value, input3.value);
tablica[1] = Number(input4.value, input5.value, input6.value);
suma = tablica[0] + tablica[1];
}
document.getElementById("div1").innerHTML = "Suma = " + suma;
</script>
</body>
</html>
First of all the last line of your script is outside the function while it uses a variable that is inside, this will not work but can easily be fixed by moving the line inside the function.
The second issue is that Number converts a string to a number. It does not sum them up. Instead move each input value to it's own Number function and add them together with the + sign.
For the difference in the two numbers you can just subtract one from the other. With Math.abs() we turn the number into a positive. This way we don't need to think about which of the two numbers is higher.
<!DOCTYPE html>
<html lang="pl">
<head>
<title> JavaScript: tablice 2-wymiarowe. </title>
<meta charset="UTF-8">
</head>
<body>
<form id="form1">
Podaj 12 liczb <br />
Pierwsza: <input id="input1" type="text" value="1" /><br />
Druga: <input id="input2" type="text" value="2" /><br />
Trzecia: <input id="input3" type="text" value="3" /><br />
Czwarta: <input id="input4" type="text" value="4" /><br />
piata: <input id="input5" type="text" value="5" /><br />
szosta: <input id="input6" type="text" value="6" /><br />
</form>
<button onclick="przetwarzanie();"> Oblicz </button>
<div id="div1"> </div>
<div id="div2"> </div>
<script>
function przetwarzanie() {
var input1 = document.getElementById("input1");
var input2 = document.getElementById("input2");
var input3 = document.getElementById("input3");
var input4 = document.getElementById("input4");
var input5 = document.getElementById("input5");
var input6 = document.getElementById("input6");
var div1 = document.getElementById("div1");
var tablica = [];
tablica[0] = Number(input1.value) + Number(input2.value) + Number(input3.value);
tablica[1] = Number(input4.value) + Number(input5.value) + Number(input6.value);
var suma = tablica[0] + tablica[1];
var roznica = Math.abs(tablica[0] - tablica[1]);
document.getElementById("div1").innerHTML = "Suma = " + suma;
document.getElementById("div2").innerHTML = "Różnica = " + roznica;
}
</script>
</body>
</html>
Suma undefined means you never created a variable and then you used it which caused the error below code is working just put all your code inside onclick function so when clicked it calculates and add it to html.
<!DOCTYPE html>
<html lang="pl">
<head>
<title> JavaScript: tablice 2-wymiarowe. </title>
<meta charset="UTF-8">
</head>
<body>
<form id="form1">
Podaj 12 liczb <br />
Pierwsza: <input id="input1" type="text" value="1" /><br />
Druga: <input id="input2" type="text" value="2" /><br />
Trzecia: <input id="input3" type="text" value="3" /><br />
Czwarta: <input id="input4" type="text" value="4" /><br />
piata: <input id="input5" type="text" value="5" /><br />
szosta: <input id="input6" type="text" value="6" /><br />
</form>
<button onclick="przetwarzanie();"> Oblicz </button>
<div id="div1"> </div>
<script>
function przetwarzanie() {
var input1 = document.getElementById("input1");
var input2 = document.getElementById("input2");
var input3 = document.getElementById("input3");
var input4 = document.getElementById("input4");
var input5 = document.getElementById("input5");
var input6 = document.getElementById("input6");
var div1 = document.getElementById("div1");
var tablica = [];
tablica[0] = Number(input1.value, input2.value, input3.value);
tablica[1] = Number(input4.value, input5.value, input6.value);
let suma = tablica[0] + tablica[1];
document.getElementById("div1").innerHTML = "Suma = " + suma;
}
</script>
</body>
</html>

jQuery/Javascript complex iterate over elements

We have a form and need to iterate over some elements to get the final sum to put in a "total" element.
E.g., here is a working starter script. It doesn't NOT iterate over the other ones. It does NOT consider the elements "item*", below, yet but should. Keep reading.
<script>
$( document ).ready(function() {
$('#taxsptotal').keyup(calcgrand);
$('#shiptotal').keyup(calcgrand);
$('#disctotal').keyup(calcgrand);
function calcgrand() {
var grandtot = parseFloat($('#subtotal').val(), 10)
+ parseFloat($("#taxsptotal").val(), 10)
+ parseFloat($("#shiptotal").val(), 10)
- parseFloat($("#disctotal").val(), 10)
$('#ordertotal').val(grandtot);
}
});
</script>
We are adding more to this. Think of having many items in a cart and each one has the same elements for the following where "i" is a number designating an individual item.
<!-- ordertotal = sum of #subtotal, #taxptotal, #shiptotal and #disctotal -->
<input type="text" id="ordertotal" name="ordertotal" value="106.49">
<input type="text" id="taxsptotal" name="taxsptotal" value="6.72">
<input type="text" id="shiptotal" name="shiptotal" value="15.83">
<input type="text" id="disctotal" name="disctotal" value="0.00">
<!-- sum of the cart "itemtotal[i]" -->
<input type="text" id="subtotal" name="subtotal" value="83.94">
<!-- cart items
User can change any itemprice[i] and/or itemquantity[i]
itemtotal[i] = sum(itemquantity[i] * itemprice[i])
-->
<input type="text" name="itemtotal[1]" value="8.97" />
<input type="text" name="itemquantity[1]" value="3" />
<input type="text" name="itemprice[1]" value="2.99" />
<input type="text" name="itemtotal[2]" value="4.59" />
<input type="text" name="itemquantity[2]" value="1" />
<input type="text" name="itemprice[2]" value="4.59" />
<input type="text" name="itemtotal[3]" value="0.99" />
<input type="text" name="itemquantity[3]" value="10" />
<input type="text" name="itemprice[3]" value="9.90" />
(1) User can change any itemprice[i] and/or itemquantity[i], so each needs a keyup. I can do that in php as it iterates over the items.
(2) These elements will have a $('.itemtotal[i]').keyup(calcgrand); (Or function other than calcgrand, if needed) statement, too. That keyup can be added by the php code as it evaluates the items in the cart.
(3) When an element is changed, then the script should automatically (a) calculate the $('[name="itemtotal[i]"]').val() and (b) replace the value for $('[name="itemtotal[i]"]').val().
(4) Then, the script above will use the $('[name="itemtotal[i]"]').val() to (a) replace the #subtotal value and (b) use that value in the equation.
Can someone help me with this? I am stuck on how to iterate over the [i] elements.
p.s. Any corrections/enhancements to the above code is appreciated, too.
Add a custom class to the desired inputs to sum:
HTML:
<input type="text" class="customclass" name=itemtotal[1] value="8.97" />
<input type="text" class="customclass" name=itemquantity[1] value="3" />
<input type="text" class="customclass" name=itemprice[1] value="2.99" />
JS:
var sum = 0;
$.each('.customclass',function(i, item){
sum = sum + Number($(this).val());
})
alert(sum);
if you for example group your inputs by giving them a class, or have each group in a div like so:
<!-- ordertotal = sum of #subtotal, #taxptotal, #shiptotal and #disctotal -->
<input type="text" id="ordertotal" name="ordertotal" value="106.49">
<input type="text" id="taxsptotal" name="taxsptotal" value="6.72">
<input type="text" id="shiptotal" name="shiptotal" value="15.83">
<input type="text" id="disctotal" name="disctotal" value="0.00">
<!-- sum of the cart "itemtotal[i]" -->
<input type="text" id="subtotal" name="subtotal" value="83.94">
<!-- cart items
User can change any itemprice[i] and/or itemquantity[i]
itemtotal[i] = sum(itemquantity[i] * itemprice[i])
-->
<div class="group">
<input type="text" name="itemtotal[1]" value="8.97" />
<input type="text" name="itemquantity[1]" value="3" />
<input type="text" name="itemprice[1]" value="2.99" />
</div>
<div class="group">
<input type="text" name="itemtotal[2]" value="4.59" />
<input type="text" name="itemquantity[2]" value="1" />
<input type="text" name="itemprice[2]" value="4.59" />
</div>
<div class="group">
<input type="text" name="itemtotal[3]" value="0.99" />
<input type="text" name="itemquantity[3]" value="10" />
<input type="text" name="itemprice[3]" value="9.90" />
</div>
Then you could do the following in javascript:
function calcSubTotal() {
$('[name^="itemtotal"]').each(function(i){
var sum = 0;
$('[name^="itemtotal"]').each(function(i){
sum += $(this).val();
});
$('#subtotal').val(sum);
});
}
$('.group').each(function(i) {
var total = $(this).find('[name^="itemtotal"]');
var qnt = $(this).find('[name^="itemquantity"]');
var price = $(this).find('[name^="itemprice"]');
total.keyup(function(e){
price.val(total.val() * qnt.val());
calcSubTotal();
});
qnt.keyup(function(e){
price.val(total.val() * qnt.val());
calcSubTotal();
});
});
$("[name^='itemprice'], [name^='itemquantity']").keyup(function(){
var input_name = $(this).attr('name');
var temp_name_split = input_name.split(/[\[\]]+/);
var temp_total = parseInt($('[name="itemquantity['+temp_name_split[1] +']"]').val()) * parseFloat($('[name="itemprice['+temp_name_split[1] +']"]').val());
$('[name="itemtotal['+temp_name_split[1]+']"]').val(temp_total.toFixed(2));
var total = 0;
$("[name^='itemtotal']").each(function() {
total += parseFloat($(this).val());
});
$('#subtotal').val(total.toFixed(2));
});

Beginner JavaScript- Results not posting in result box

Hey all i've just begun javascript programming and I can't figure out why my program isn't "doing the math". When I input numbers into the boxes it wont give me results in the result boxes at the bottom. I'm not sure if I need to separate the script into multiple calculations or leave it the way it is. This is my first project with javascript and I am not sure if I missed something or not. Any help will be very appreciated.
<!DOCTYPE html>
<html>
<head>
<title>Javascript Financial Formulas</title>
<script type="text/javascript">
function calculateLoan(){
var Profit = parseFloat(document.getElementID("Profit").value);
var AverageNumberOfShares = parseInt(document.getElementById("AverageNumberOfShares").value);
var PricePerShare = parseFloat(document.getElementById("PricePerShare").value);
var TotalAssets = parseFloat(document.getElementID("TotalAssets").value);
var IntangibleAssets = parseFloat(document.getElementID("IntangibleAssets").value);
var Liabilities = parseFloat(document.getElementID("Liabilities").value);
var PricePerShare = parseFloat(document.getElementID("PricePerShare").value);
var EarningsPerShare = parseFloat(document.getElementID("EarningsPerShare").value);
var PERatio = parseFloat(document.getElementID("PERatio").value);
var PercentExpectedGrowth = parseFloat(document.getElementID("PercentExpectedGrowth").value);
var EarningsPerShare;
var PriceToBook;
var PERatio;
var PriceToEarningsGrowth;
EarningsPerShare = Profit / AverageNumberOfShares;
PriceToBook = PricePerShare / (TotalAssets - (IntangibleAssets + Liabilities));
PERatio = PricePerShare / EarningsPerShare;
PriceToEarningsGrowth = PERatio / PercentExpectedGrowth;
document.getElementById("EarningsPerShare").value = EarningsPerShare;
document.getElementById("PriceToBook").value = PriceToBook;
document.getElementById("PERatio").value = PERatio;
document.getElementById("PriceToEarningsGrowth").value = PriceToEarningsGrowth;
}
</script>
</head>
<body>
<h1>Javascript Financial Formulas</h1>
<p>To use, please input financial information and press calculate<p>
<form name="Financial Formulas">
<p>Earnings per share:<p>
Profit:
<input type = "text" id="Profit" name="Profit" value="" /><br />
Average number of shares:
<input type = "text" id="AverageNumberOfShares" name="AverageNumberOfShares" value="" /><br />
<p>Price to Book:<p>
Price per share:
<input type = "text" id="PricePerShare" name="PricePerShare" value="" /><br />
Total Assets:
<input type = "text" id="TotalAssets" name="TotalAssets" value="" /><br />
Intangible Assets:
<input type = "text" id="IntangibleAssets" name="IntangibleAssets" value="" /><br />
Liabilities:
<input type = "text" id="Liabilities" name="Liabilities" value="" /><br />
<p>PE Ratio:<p>
Price per share:
<input type = "text" id="PricePerShare" name="PricePerShare" value="" /><br />
Earnings per share:
<input type = "text" id="EarningsPerShare" name="EarningsPerShare" value="" /><br />
<p>Price to Earnings Growth:<p>
PE Ratio:
<input type = "text" id="PERatio" name="PERatio" value="" /><br />
Percent Expected Growth:
<input type = "text" id="PercentExpectedGrowth" name="PercentExpectedGrowth" value="" /><br />
<input type = "button" id="calculate" name="Calculate" value="Calculate" onclick="calculateLoan();" />
<input type = "reset" id="Reset" name="Reset" value="Reset" /><br />
<br>
Earnings per share:
<input type = "text" id="EarningsPerShare" name="EarningsPerShare:" value="" /><br />
Price to Book:
<input type = "text" id="PriceToBook" name="PriceToBook:" value="" /><br />
PE Ratio:
<input type = "text" id="PERatio" name="PERatio:" value="" /><br />
Price to Earnings Growth:
<input type = "text" id="PriceToEarningsGrowth" name="PriceToEarningsGrowth:" value="" /><br />
</form>
</body>
</html>
If it's your first javascript program, you'll be happy to know there is a console output in browsers. Just press F12 and you'll see the error printed. :)
In your case, the error is about getElementById that you have wrongly spelled getElementId.
Error says :
Uncaught TypeError: document.getElementID is not a function

How to put the value of <Input type=date/> to var outside the JavaScript?

Im Trying to put the Value of dtpFrom to var FDate
I know my Javascript is wrong. I provided them so that you may know what I need to do.
var FDate = "";
var TDate = "";
<script>
function myFunction() {
document.getElementById("FDate").value = document.getElementById("dtpFrom").value;
document.getElementById("TDate").value = document.getElementById("dtpTo").value;
}
</script>
<p>
<strong><b>Find by MAWB: #Html.TextBox("searchstring")</b></strong>
<strong><b>From: #Html.TextBox("fromDate", FDate)</b></strong>
<strong><b>To: #Html.TextBox("toDate", TDate)</b></strong>
<input type="Date" id="dtpFrom" onchange="myFunction()" />
<input type="Date" id="dtpTo" />
<input type="submit" value="Search" />
</p>
https://jsfiddle.net/0zfjy75r/1/
var FDate = "<span id="FDate"></span>";
var TDate = "<span id="TDate"></span>";
<script>
function myFunction() {
document.getElementById("FDate").innerHTML = document.getElementById("dtpFrom").value;
document.getElementById("TDate").innerHTML = document.getElementById("dtpTo").value;
}
</script>
<p>
<strong><b>Find by MAWB: #Html.TextBox("searchstring")</b></strong>
<strong><b>From: #Html.TextBox("fromDate", FDate)</b></strong>
<strong><b>To: #Html.TextBox("toDate", TDate)</b></strong><br>
<input type="Date" id="dtpFrom" onchange="myFunction()" />
<input type="Date" id="dtpTo" />
<input type="submit" value="Search" />
</p>

Calculate total based on input values that were calculated based on other input values

I'm building a time tracking system. Users would enter hours worked during the week. We have biweekly pay periods (2 weeks). Once daily hours have been entered, onChange is used trigger a javascript function that calculates weekly total and outputs it to read-only input text boxes (txtWeek1Total and txtWeek2Total). That part works.
The next step is to automatically calculate the pay period total (week 1 + week 2) based on the input values from txtWeek1Total and txtWeek2Total. Currently, I'm using onChange on these text boxes but it does not fire. It gets triggered only if I manually input a value into the weekly total text boxes. Even if these values get updated automatically when the user enter daily hours.
html:
<input type="text" id="week1SundayTotal" onChange="calculateWeeklyHours('week1');" /><br />
<input type="text" id="week1MondayTotal" onChange="calculateWeeklyHours('week1');" /><br />
<input type="text" id="week1TuesdayTotal" onChange="calculateWeeklyHours('week1');" /><br />
<input type="text" id="week1WednesdayTotal" onChange="calculateWeeklyHours('week1');" /><br />
<input type="text" id="week1ThursdayTotal" onChange="calculateWeeklyHours('week1');" /><br />
<input type="text" id="week1FridayTotal" onChange="calculateWeeklyHours('week1');" /><br />
<input type="text" id="week1SaturdayTotal" onChange="calculateWeeklyHours('week1');" /><br />
<input type="text" id="week1WeekTotal" onChange="calculateTotal();" /><br /><br />
<input type="text" id="week2SundayTotal" onChange="calculateWeeklyHours('week2');" /><br />
<input type="text" id="week2MondayTotal" onChange="calculateWeeklyHours('week2');" /><br />
<input type="text" id="week2TuesdayTotal" onChange="calculateWeeklyHours('week2');" /><br />
<input type="text" id="week2WednesdayTotal" onChange="calculateWeeklyHours('week2');" /><br />
<input type="text" id="week2ThursdayTotal" onChange="calculateWeeklyHours('week2');" /><br />
<input type="text" id="week2FridayTotal" onChange="calculateWeeklyHours('week2');" /><br />
<input type="text" id="week2SaturdayTotal" onChange="calculateWeeklyHours('week2');" /><br />
<input type="text" id="week2WeekTotal" onChange="calculateWeeklyHours('week2');" /><br />
<input type="text" id="Total" />
javascript:
function calculateWeeklyHours(week) {
var sunday = document.getElementById(week + 'SundayTotal').value;
var monday = document.getElementById(week + 'MondayTotal').value;
var tuesday = document.getElementById(week + 'TuesdayTotal').value;
var wednesday = document.getElementById(week + 'WednesdayTotal').value;
var thursday = document.getElementById(week + 'ThursdayTotal').value;
var friday = document.getElementById(week + 'FridayTotal').value;
var saturday = document.getElementById(week + 'SaturdayTotal').value;
var weekTotal = document.getElementById(week + 'WeekTotal');
weekTotal.value = Number(sunday) + Number(monday) + Number(tuesday) + Number(wednesday) + Number(thursday) + Number(friday) + Number(saturday);
}
function calculateTotal() {
var week1 = document.getElementById('w1WeekTotal').value;
var week2 = document.getElementById('w2WeekTotal').value;
var total = document.getElementById('Total');
total.value = Number(week1) + Number(week2);
}
Use onkeyup event instead of onchange event - check this (http://jsfiddle.net/JrDd3/2/)
Just call the calculateTotal function at the end of the calculateWeeklyHours function
Example: http://jsfiddle.net/JrDd3/

Categories