I'm trying to create an algorithm that divides a single number three times.
I've created this code, but it for some reason it doesn't work and I've got no clue why.
Could some one give me insight into what i'm doing wrong?
HTML
<form id="frm1">
Budget: <input id="budget" type="text" name="budget" value="110"><br>
<br>
Domestic:
<input id="low" type="text" name="low" value="20">%<br>
<input id="lowresult" type="text" name="low" oninput="calculate()"><br>
Continental:
<input id="med" type="text" name="med" value="30">% <br>
<input id="medresult" type="text" name="med" oninput="calculate()"><br>
International:
<input id="high" type="text" name="high" value="50">% <br>
<input id="highresult" type="text" name="high" oninput="calculate()"><br>
<br>
</form>
Javascript
function calculate() {
var budget = document.getElementById("budget").value;
var low = document.getElementById('low').value;
var med = document.getElementById('med').value;
var high = document.getElementById('high').value;
var lowResult = document.getElementById('lowresult');
var medResult = document.getElementById('medresult');
var highResult = document.getElementById('highresult');
var lowFinalResult = (budget /100)*low;
lowResult.value = lowResult;
var medFinalResult = (budget /100)*med;
medResult.value = medResult;
var highFinalResult = (budget /100)*high;
highResult.value = highResult;
}
adjust javascript
this
var lowFinalResult = (budget /100)*low;
lowResult.value = lowFinalResult;
insetad of
var lowFinalResult = (budget /100)*low;
lowResult.value = lowResult;
full code
function calculate() {
var budget = document.getElementById("budget").value;
var low = document.getElementById('low').value;
var med = document.getElementById('med').value;
var high = document.getElementById('high').value;
var lowResult = document.getElementById('lowresult');
var medResult = document.getElementById('medresult');
var highResult = document.getElementById('highresult');
var lowFinalResult = (budget /100)*low;
lowResult.value = lowFinalResult;
var medFinalResult = (budget /100)*med;
medResult.value = medFinalResult;
var highFinalResult = (budget /100)*high;
highResult.value = highFinalResult;
}
You wrote in the comment that you're "trying to input one amount into the 'budget' input". So I'd like to add that you do that calculate() in the budget input:
<form id="frm1">
Budget: <input id="budget" type="text" name="budget"
value="110" oninput="calculate()"><br>
So the oninput attribute of the other inputs can be removed.
Related
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();">
What i am trying to do now is have separate calculation when a radio button is highlighted for particular fields... in this case if the radio button is highlightedior "yearly" i want the user input of the text field to be calculated maintFees * 1 = x variable and show that output in maintTimesTwelve.
if not highlighted for "yearly" i want it to be calculated by maintFees * 12. and shown in maintTimesTwelve.
js fiddle:https://jsfiddle.net/ryx4qt0d/
here is the copy of my code
// start of variables
function yearlyPayment(){
var monthlyPayment = parseInt(document.getElementById("monthlyPayment").value);
var maintFees = parseInt(document.getElementById("maintFees").value);
var memFees = parseInt(document.getElementById("memFees").value);
var exchFees = parseInt(document.getElementById("exchFees").value);
var result = (monthlyPayment?monthlyPayment:0) + (maintFees?maintFees:0) + (memFees?memFees:0) + (exchFees?exchFees:0);
document.getElementById("txtResult").value = result;}
//first function after submission
function mpTwelve(){
var monPay = parseInt(document.getElementById("monthlyPayment").value);
var monTwe = monPay * 12;
document.getElementById("mpTimesTwelve").value = monTwe;}
// sencond function
function maintTwelve(){
var maintPay = parseInt(document.getElementById("maintFees").value);
var maintTwe = maintPay * 12;
var x = maintPay * 1;
if (document.getElementByClass("year").checked){
document.getElementById("mantTimesTwelve").value = x;
}
else{
document.getElementById("maintTimesTwelve").value = maintTwe;}
}
// third function
function yearlyTen(){
var yearPay = parseInt(document.getElementById("txtResult").value);
var yearTen = yearPay * 120;
document.getElementById("totalYearly").value = yearTen;}
//4th function
function yearlyTenMaint(){
var tenMain = parseInt(document.getElementById("maintTimesTwelve").value);
var tenMainTen = (tenMain * 120) * .5;
document.getElementById("maintTenYear").value = tenMainTen;}
//fifth function
function totalMeEx(){
var meEx = parseInt(document.getElementById("memFees").value);
var exMe = parseInt(document.getElementById("exchFees").value);
var totalExMe = (meEx + exMe) * 120;
document.getElementById("totalMemDues").value = totalExMe;
}
<div>
<p>
Monthly payment:<br>
<input type="text" id="monthlyPayment" class="input"/><br>
Maintenance fees:<br>
<input style="margin-left: 79px" type="text" id="maintFees" class="input"/>
<input type="radio" id="year" name="year" class="year">
<label for="year"> Yearly </label><br>
Membership dues:<br><br>
<input type="text" id="memFees" class="input"/><br>
xchange Fees<br>
<input type="text" id="exchFees" class="input"/><br>
<br>
Annual timeshare vacation cost:<br>
<input type="text" id="txtResult"/><br>
Monthly payment x 12<br>
<input type="text" id="mpTimesTwelve"/><br>
Maintenance fees x 12<br>
<input type="text" id="maintTimesTwelve"/><br>
Total yearly payment x10 years:<br>
<input type="text" id="totalYearly"/><br>
Yearly Mainteneance over 10 years w/ 5% increase:<br>
<input type="text" id="maintTenYear"/><br>
Membership Dues + Exchange Fees x 10 years:<br>
<input type="text" id="totalMemDues"/><br>
<button onclick="yearlyPayment(); mpTwelve(); maintTwelve();yearlyTen(); yearlyTenMaint();totalMeEx();">calculate</button><br>
</p></div>
if (document.getElementByClass("year").checked){ should be if (document.getElementsByClassName("year")[0].checked){ because getElementsByClassName() returns a collection. Can be simplified by using if (document.querySelector(".year").checked){
You had a typo here: document.getElementById("mantTimesTwelve") mant should be maint
Please: Check the console everytime a script doesn't run, it's so easy to find this kind of errors.
// start of variables
function yearlyPayment(){
var monthlyPayment = parseInt(document.getElementById("monthlyPayment").value);
var maintFees = parseInt(document.getElementById("maintFees").value);
var memFees = parseInt(document.getElementById("memFees").value);
var exchFees = parseInt(document.getElementById("exchFees").value);
var result = (monthlyPayment?monthlyPayment:0) + (maintFees?maintFees:0) + (memFees?memFees:0) + (exchFees?exchFees:0);
document.getElementById("txtResult").value = result;}
//first function after submission
function mpTwelve(){
var monPay = parseInt(document.getElementById("monthlyPayment").value);
var monTwe = monPay * 12;
document.getElementById("mpTimesTwelve").value = monTwe;}
// sencond function
function maintTwelve(){
var maintPay = parseInt(document.getElementById("maintFees").value);
var maintTwe = maintPay * 12;
var x = maintPay * 1;
if (document.getElementsByClassName("year")[0].checked){
document.getElementById("maintTimesTwelve").value = x;
}
else{
document.getElementById("maintTimesTwelve").value = maintTwe;
}
}
// third function
function yearlyTen(){
var yearPay = parseInt(document.getElementById("txtResult").value);
var yearTen = yearPay * 120;
document.getElementById("totalYearly").value = yearTen;}
//4th function
function yearlyTenMaint(){
var tenMain = parseInt(document.getElementById("maintTimesTwelve").value);
var tenMainTen = (tenMain * 120) * .5;
document.getElementById("maintTenYear").value = tenMainTen;}
//fifth function
function totalMeEx(){
var meEx = parseInt(document.getElementById("memFees").value);
var exMe = parseInt(document.getElementById("exchFees").value);
var totalExMe = (meEx + exMe) * 120;
document.getElementById("totalMemDues").value = totalExMe;
}
<div>
<p>
Monthly payment:<br>
<input type="text" id="monthlyPayment" class="input"/><br>
Maintenance fees:<br>
<input style="margin-left: 79px" type="text" id="maintFees" class="input"/>
<input type="radio" id="year" name="year" class="year">
<label for="year"> Yearly </label><br>
Membership dues:<br><br>
<input type="text" id="memFees" class="input"/><br>
xchange Fees<br>
<input type="text" id="exchFees" class="input"/><br>
<br>
Annual timeshare vacation cost:<br>
<input type="text" id="txtResult"/><br>
Monthly payment x 12<br>
<input type="text" id="mpTimesTwelve"/><br>
Maintenance fees x 12<br>
<input type="text" id="maintTimesTwelve"/><br>
Total yearly payment x10 years:<br>
<input type="text" id="totalYearly"/><br>
Yearly Mainteneance over 10 years w/ 5% increase:<br>
<input type="text" id="maintTenYear"/><br>
Membership Dues + Exchange Fees x 10 years:<br>
<input type="text" id="totalMemDues"/><br>
<button onclick="yearlyPayment(); mpTwelve(); maintTwelve();yearlyTen(); yearlyTenMaint();totalMeEx();">calculate</button><br>
</p></div>
As I mention in the title I have three input in HTML:
<input type="number" name="time" id="time">
<input type="time" name="hour_start" id="hour_start">
<input type="time" name="hour_final" id="hour_final">
and JS:
<script>
$("#time").change(function () {
var time = $('#time').val();
var start = $('#hour_start').val();
var convert = Math.floor(time/60);
var final = start + convert;
$('#hour_final').val(final);
});
</script>
The calculation is done without using a button.
Enter image description here
Javascript answser ( as you asking) :
const myForm = document.querySelector('#my-Form')
, z2 = v=>('00'+v).slice(-2) // like padStart(2.'0')
myForm.time.oninput=_=>
{
let inDate = myForm.hour_start.valueAsDate
, h_UTC = inDate.getUTCHours()
, m_UTC = inDate.getUTCMinutes()
, nTim = (h_UTC * 60) + m_UTC + myForm.time.valueAsNumber
h_UTC = Math.trunc(nTim/60) % 24
m_UTC = nTim % 60
inDate.setUTCHours(h_UTC)
inDate.setUTCMinutes(m_UTC)
myForm.hour_final.valueAsDate = inDate
}
myForm.onsubmit=e=>
{
e.prventdefault() // just for test
}
<form action="xxx" id="my-Form">
<input type="number" name="time" value="0" min="0" max="2000">
<input type="time" name="hour_start" value="13:30">
<input type="time" name="hour_final" value="13:30">
</form>
This question already has answers here:
Reading numbers from inputs with JavaScript always returns NaN
(8 answers)
Closed 7 years ago.
I'm attempting to write a simple JavaScript program that calculates the cost of gas based on some parameters from a form. Upon form submission, I get a NaN error inside of the "calculatedMonthlyCost" div.
Can anybody tell me what I'm doing wrong? Is there a better way of doing this?
<form>
Cost of Gas: <input type="text" placeholder="ex: 3.10" name="costOfGas"/>
<br>
Vehicle MPG: <input type="text" placeholder="ex: 30" name="vehicleMPG"/>
<br>
How many miles do you drive to work (one-way): <input type="text" placeholder="ex: 10" name="numMiles"/>
<br>
<input type="submit" value="Submit">
<br>
</form>
<div id="calculatedMonthlyCost"></div>
<script>
var calcCost = function (costOfGas, vehicleMPG, numMiles) {
var dailyCost = (costOfGas / vehicleMPG) * (numMiles * 2);
var weeklyCost = dailyCost * 5;
var monthlyCost = weeklyCost * 4;
return {
dailyCost: dailyCost,
weeklyCost: weeklyCost,
monthlyCost: monthlyCost
};
}
var userCostOfGas = document.forms[0].costOfGas.value;
var userMPG = document.forms[0].vehicleMPG.value;
var userNumMiles = document.forms[0].numMiles.value;
document.forms[0].onsubmit = function(e) {
e.preventDefault();
var costs = calcCost(userCostOfGas, userMPG, userNumMiles);
var calculatedMonthlyCost = document.getElementById("calculatedMonthlyCost");
calculatedMonthlyCost.innerHTML = costs.weeklyCost;
};
</script>
You were getting the values on page load (when they were empty). You just need to get the values inside the onsubmit event listener, and to convert them to Numbers.
var calcCost = function (costOfGas, vehicleMPG, numMiles) {
var dailyCost = (costOfGas / vehicleMPG) * (numMiles * 2);
var weeklyCost = dailyCost * 5;
var monthlyCost = weeklyCost * 4;
return {
dailyCost: dailyCost,
weeklyCost: weeklyCost,
monthlyCost: monthlyCost
};
}
document.forms[0].onsubmit = function(e) {
e.preventDefault();
var userCostOfGas = +document.forms[0].costOfGas.value; // < Move these lines here and
var userMPG = +document.forms[0].vehicleMPG.value; // < add a plus sign before them
var userNumMiles = +document.forms[0].numMiles.value; // <
var costs = calcCost(userCostOfGas, userMPG, userNumMiles);
var calculatedMonthlyCost = document.getElementById("calculatedMonthlyCost");
calculatedMonthlyCost.innerHTML = costs.weeklyCost;
};
<form>
Cost of Gas: <input type="text" placeholder="ex: 3.10" name="costOfGas"/>
<br>
Vehicle MPG: <input type="text" placeholder="ex: 30" name="vehicleMPG"/>
<br>
How many miles do you drive to work (one-way): <input type="text" placeholder="ex: 10" name="numMiles"/>
<br>
<input type="submit" value="Submit">
<br>
</form>
<div id="calculatedMonthlyCost"></div>
If you only want 2 decimals, you can change this line:
calculatedMonthlyCost.innerHTML = (costs.weeklyCost).toFixed(2);
Demo:
var calcCost = function (costOfGas, vehicleMPG, numMiles) {
var dailyCost = (costOfGas / vehicleMPG) * (numMiles * 2);
var weeklyCost = dailyCost * 5;
var monthlyCost = weeklyCost * 4;
return {
dailyCost: dailyCost,
weeklyCost: weeklyCost,
monthlyCost: monthlyCost
};
}
document.forms[0].onsubmit = function(e) {
e.preventDefault();
var userCostOfGas = +document.forms[0].costOfGas.value; // < Move these lines here and
var userMPG = +document.forms[0].vehicleMPG.value; // < add a plus sign before them
var userNumMiles = +document.forms[0].numMiles.value; // <
var costs = calcCost(userCostOfGas, userMPG, userNumMiles);
var calculatedMonthlyCost = document.getElementById("calculatedMonthlyCost");
calculatedMonthlyCost.innerHTML = (costs.weeklyCost).toFixed(2);
};
<form>
Cost of Gas: <input type="text" placeholder="ex: 3.10" name="costOfGas"/>
<br>
Vehicle MPG: <input type="text" placeholder="ex: 30" name="vehicleMPG"/>
<br>
How many miles do you drive to work (one-way): <input type="text" placeholder="ex: 10" name="numMiles"/>
<br>
<input type="submit" value="Submit">
<br>
</form>
<div id="calculatedMonthlyCost"></div>
You save the value of your inputs before the onsubmit method is called. This actually saves a blank value since the variables are set before the user inputs a value and it's not dynamic. The values need to be checked on submit.
document.forms[0].onsubmit = function(e) {
var userCostOfGas = parseInt(document.forms[0].costOfGas.value,10);
var userMPG = parseInt(document.forms[0].vehicleMPG.value,10);
var userNumMiles = parseInt(document.forms[0].numMiles.value,10);
e.preventDefault();
var costs = calcCost(userCostOfGas, userMPG, userNumMiles);
var calculatedMonthlyCost = document.getElementById("calculatedMonthlyCost");
calculatedMonthlyCost.innerHTML = costs.weeklyCost;
};
I've been trying to convert a label to an int to do an equation. I haven't been able to use ConvertToInt32() or ParseInt(). I've been getting back NaN each time. Please help! Here's my code:
<div id="width"> <strong>Roll Width: </strong><label id="lblRollWidth" type="number">25</label></div>
</asp:Panel>
</div>
</div>
<input type="text" name="input1" id="input1" value="">
<input type="text" name="input2" id="input2" value="">
Calculate
<input type="text" name="output" id="output" value="">
<script>
function calc(){
var textValue1 = document.getElementById('input1').value;
var textValue2 = document.getElementById('input2').value;
var textValue3 = document.getElementById('lblRollWidth').value;
document.getElementById('output').value = textValue1 * textValue2 * textValue3;
}
</script>
change :
var textValue3 = document.getElementById('lblRollWidth').value;
to
var textValue3 = +document.getElementById('lblRollWidth').innerText;
because it is a label, therefore to get its value you have to use .innerText.
Also, not mandatory, but recommendended, change:
var textValue1 = document.getElementById('input1').value;
var textValue2 = document.getElementById('input2').value;
to:
var textValue1 = +document.getElementById('input1').value;
var textValue2 = +document.getElementById('input2').value;
So that they will be casted as numbers.
Fiddle:
http://jsfiddle.net/m1brLkqx/
Also, as a side note, NaN is being thrown because of the label, the rest was working.