Using Javascript to calculate form fields -- get NaN as a result - javascript

I have created a short form that is supposed to calculate values based on user input. I've got most of it figured out but can't seem to get the results to show up in the totals field. Instead, I get NaN.
I'm trying to use parseInt but haven't had any luck yet.
Here is what I have so far:
The Javascript:
var AdPrice = document.getElementsByTagName('input') = 0;
var ColorCharge = document.getElementsByTagName('input') = 0;
var WebAd = document.getElementsByTagName('input') = 0;
var AdSubtotal = 0;
var DownPayment = document.getElementsByTagName('input') = 0;
var TotalPrice = 0;
var Payments = document.getElementsByTagName('input') = 0;
var TotalPayment = 0;
function updateTotal()
{
var subtotal = AdPrice + ColorCharge + WebAd;
var total = subtotal - DownPayment;
var totalmonthlypayment = total / Payments;
parseFloat(document.getElementById('AdSubtotal').value = subtotal);
parseFloat(document.getElementById('TotalPrice').value = total);
parseFloat(document.getElementById('Payment').value = totalmonthlypayment);
}
The HTML:
<fieldset>
<legend>Payment Details</legend>
Ad Charge $
<input type="text" name="AdPrice" id="AdPrice" class="medium" onChange="updateTotal()" /><br />
Color Charge +
<input type="text" name="ColorCharge" id="ColorCharge" class="medium" onChange="updateTotal()" /><br />
Web Ad +
<input type="text" name="WebAd" id="WebAd" class="medium" onChange="updateTotal()" /><br />
Subtotal =
<input type="text" name="AdSubtotal" id="AdSubtotal" readonly class="medium" /><br />
Down Payment -
<input type="text" name="DownPayment" id="DownPayment" class="medium" onChange="updateTotal()" /><br />
Total =
<input type="text" name="TotalPrice" id="TotalPrice" readonly class="medium" /><br /><br />
# Consec. Payments \
<input type="text" name="Payments" id="Payments" class="medium" onChange="updateTotal" /><br />
Amt Each Payment $
<input type="text" name="Payment" id="Payment" class="medium" readonly /><br /><br />
<input type="checkbox" name="ProratedCheck" id="ProratedCheck" /> <span style="margin-right:10px;">Prorated/Length</span><input type="text" name="ProratedLength" id="ProratedLength" />
</fieldset>
I also have a fiddle:
http://jsfiddle.net/kjetterman/eHQV4/10/

There were several errors on the javascript that you need to work on, as mentioned on the comments for your question you should use getElementById for retrieving DOM elements, other issue you had is that your code was running as soon as the browser gets the response which at the moment might not have the DOM ready for work so all your references were coming back as NULL. Here's the working version, you still need to add some validation for when the initial values are zeroes so you don't get NaN as result of operations.
http://jsfiddle.net/Wy7kE/2/

Division by zero (subtotal) at the beginning.
And:
Does this kind of binding work? I think not. Very new to me.......
What about placing the "getElements"-lines inside the method?

Related

JavaScript function not taking/setting form data [duplicate]

This question already has answers here:
How to use document.getElementByName and getElementByTag?
(6 answers)
Closed 5 years ago.
I am writing a simple online order form for widgets which is supposed to take the order of 3 widgets, add them together and give a total number and a cost. However, when the button is clicked to go into the function, nothing happens. I am not sure whether the fault is in getting the data into the function or getting it out of the function.
function cal() {
var wid1 = document.getElementById("widg1").value;
var wid2 = document.getElementById("widg2").value;
var wid3 = document.getElementById("widg3").value;
var tot = (wid1 + wid2 + wid3);
var dollars = ((wid1 * 12.45) + (wid2 * 15.34) + (wid3 * 28.99));
document.getElementByName("total").value = tot;
document.getElementByName("money").value = dollars;
}
<form name="widgets">
widget model 37AX-L:<br>
<input type="text" id="widg1" name="37AX-L" value=0><br> widget model 42XR-J:<br>
<input type="text" id="widg2" name="42XR-J" value=0><br> widget model 93ZZ-A:<br>
<input type="text" id="widg3" name="93ZZ-A" value=0><br>
<br>
<input type="button" name="B1" value="Calculate" onclick="cal()"><br>
</form>
<input type="text" name="total" id="total"> total widgets <br>
<input type="text" name="money" id="money"> total dollars
You omitted s in Elements.
document.getElementsByName("total")[0].value=tot not document.getElementByName("total")
<form name="widgets">
widget model 37AX-L:<br>
<input type="text" id="widg1" name="37AX-L" value=0><br>
widget model 42XR-J:<br>
<input type="text" id="widg2" name="42XR-J" value=0><br>
widget model 93ZZ-A:<br>
<input type="text" id="widg3" name="93ZZ-A" value=0><br>
<br>
<input type="button" name="B1" value="Calculate" onclick="cal()"><br>
</form>
<input type="text" name="total" id="total"> total widgets <br>
<input type="text" name="money" id="money"> total dollars
<script>
function cal(){
var wid1 = document.getElementById("widg1").value;
var wid2 = document.getElementById("widg2").value;
var wid3 = document.getElementById("widg3").value;
var tot = (wid1+wid2+wid3);
var dollars = ((wid1*12.45)+(wid2*15.34)+(wid3*28.99));
document.getElementsByName("total")[0].value=tot;
document.getElementsByName("money")[0].value=dollars;
}
</script>

Using parantheses around variables in Javascript to change priority in math calculations

I'm exercising in javascript calculations using a combination of maths and variables and i'm finding a difficulty on using the right way parentheses. For example i want to do the following calculation [(4,95/ans2)-4,5]*100 where ans2 is a calculated variable. In the last field i get 45.000 and i should take - 4.046 ... if the input in the first and second fields was 2 + 2
<form name="Calcultor" Method="Get" id='form1'>First Number:
<input type="text" name="first" size="35" id="first">+ Second Number:
<input type="text" name="second" size="35" id="second">
<br>Answer:
<input type="text" name="ans" size="35" id="ans" />
<input type="text" name="ans2" size="35" id="ans2" />
<input type="text" name="ans3" size="35" id="ans3" />
<button type="button" onclick="Calculate();">Calculate</button>
</form>
<script>
function Calculate() {
var first = document.getElementById('first').value;
var second = document.getElementById('second').value;
var ans = document.getElementById('ans').value;
var ans2 = document.getElementById('ans2').value;
document.getElementById('ans').value = parseInt(first) + parseInt(second);
document.getElementById('ans2').value = 1.112 - 0.00043499 * parseInt(document.getElementById('ans').value) + 0.00000055 * Math.pow(parseInt(document.getElementById('ans').value), 2) - 0.00028826;
/* in the following line i can't figure how to use with a proper way parentheses to prioriterize the calculations with the way i mentioned in the example before the code snippet*/
document.getElementById('ans3').value = [( 4.95 / parseInt(document.getElementById('ans2').value)) - 4.5] * 100;
}
</script>
The issue was in this row: document.getElementById('ans3').value = [( 4.95 / parseInt(document.getElementById('ans2').value)) - 4.5] * 100;. You need to use () instead of [] for grouping and you also don't need to parseInt the value. Here is the working snippet:
function Calculate() {
var first = document.getElementById('first').value;
var second = document.getElementById('second').value;
var ans = document.getElementById('ans').value;
var ans2 = document.getElementById('ans2').value;
document.getElementById('ans').value = parseInt(first) + parseInt(second);
document.getElementById('ans2').value = 1.112 - 0.00043499 * parseInt(document.getElementById('ans').value) + 0.00000055 * Math.pow(parseInt(document.getElementById('ans').value), 2) - 0.00028826;
/* in the following line i can't figure how to use with a proper way parentheses to prioriterize the calculations with the way i mentioned in the example before the code snippet*/
document.getElementById('ans3').value = ((4.95 / document.getElementById('ans2').value) - 4.5) * 100
}
<form name="Calcultor" Method="Get" id='form1'>First Number:
<input type="text" name="first" size="35" id="first">+ Second Number:
<input type="text" name="second" size="35" id="second">
<br>Answer:
<input type="text" name="ans" size="35" id="ans" />
<input type="text" name="ans2" size="35" id="ans2" />
<input type="text" name="ans3" size="35" id="ans3" />
<button type="button" onclick="Calculate();">Calculate</button>
</form>

Multiplying calculator

I am trying to create a simple calculator that takes a number from 1 text box and after hitting a submit button it takes the number and multiplies it by 92 then puts it in a read only box.
This is what I have so far:
<form name="1star">
<input type="text" name="input"/>
<input type="button" value="Enter" OnClick="1star.output.value == 1star.input.value * 92"/>
<br/>
<input type="text" name="output" readonly="readonly" />
</form>
This is not working and I could use some help. I know its easy but I am very new to js and I'm not understanding why this isn't working.
<form name="onestar">
<input type="text" name="input"/>
<input type="button" value="Enter" OnClick="onestar.output.value = onestar.input.value * 92"/>
<br/>
<input type="text" name="output" readonly="readonly" />
</form>
An identifier cannot start with a digit in JavaScript, so 1star is an error. Also, you wanted = (assignment), not == (comparison).
That said, there are a number of outdated or beginner practices above. If I was writing it, I would separate the script from the markup, and I'd use document.getElementById to fetch the element rather than relying on implicit variables defined by name. I would also explicitly parse the string into a number. But for now no need to worry about it too much. Even though the code seems much more complicated at first glance, it's all things that will make your life easier later, with bigger programs.
var input = document.getElementById('input');
var output = document.getElementById('output');
var button = document.getElementById('button');
button.addEventListener('click', function(evt) {
var value = parseInt(input.value, 10);
if (!isNaN(value)) {
output.value = value * 92;
}
});
<form>
<input type="text" id="input"/>
<input type="button" id="button" value="Enter"/>
<br/>
<input type="text" id="output" readonly="readonly" />
</form>

Javascript to show price with 2 decimal places

I have a form that has 5 fields for a user to put how much they want to pay for 5 separate items. I then have it automatically totaling it at the bottom. Since this total goes to a payment gateway I need to force it to round to 2 decimal places.
Can someone tell me how to change the code to do this? I am a newbie with this.
Here is the code I have:
<script>
function calculatepay(pay) {
var one = document.getElementById(pay + 'Student1Total').value;
var two = document.getElementById(pay + 'Student2Total').value;
var three = document.getElementById(pay + 'Student3Total').value;
var four = document.getElementById(pay + 'Student4Total').value;
var five = document.getElementById(pay + 'Student5Total').value;
var payTotal = document.getElementById(pay + 'payTotal');
payTotal.value = Number(one) + Number(two) + Number(three) + Number(four) + Number(five) ;
calculateTotal();
}
</script>
<input type="text" id="pay1Student1Total" name="data1" onKeyUp="calculatepay('pay1');" /><br />
<input type="text" id="pay1Student2Total" name="data2" onKeyUp="calculatepay('pay1');" /><br />
<input type="text" id="pay1Student3Total" name="data3" onKeyUp="calculatepay('pay1');" /><br />
<input type="text" id="pay1Student4Total" name="data4" onKeyUp="calculatepay('pay1');" /><br />
<input type="text" id="pay1Student5Total" name="data5" onKeyUp="calculatepay('pay1');" /><br /><br /><br />
Total:
<input type="text" id="pay1payTotal" onKeyUp="calculateTotal();" value="0"/><br /><br />
You can use the toFixed(2) function in JavaScript to convert numbers to a fixed value.
It's used like this:
payTotal.value.toFixed(2)
So if the input value is 1, it'll look like 1.00
You can use .toFixed() method :
var x = 5.1232;
console.log(x.toFixed(2));
Use this : toFixed(2); It will round to two decimal places
You can use Math.round(num * 100) / 100

Subtract an integer from a calculated total

I've built a script to add quantities/units and generate a total that displays sales tax.
How can I get this calculator to recognise #discount and subtract it from the total before the GST (10% sales tax) is calculated and added?
Also, is it possible to generate the total when the page loads? Instead of a user having to press the 'Generate total' button?
HTML
<ul>
<li> Item 1 (<input type="text" name="others" size="4" value="5" readonly="readonly" class="readonly_field"/> units)</li>
<li> Item 2 (<input type="text" name="others" size="4" value="1" readonly="readonly" class="readonly_field"/> units)</li>
<li> Item 3 (<input type="text" name="others" size="4" value="3" readonly="readonly" class="readonly_field"/> units)</li>
</ul>
<input type="button" value="Generate Total" onclick="total()" /><br><br>
Discount <input type="text" id="discount" name="discount" value="500"/><br><br>
Total Units: <input type="text" id="units_total" name="units_total" readonly="readonly" /><br>
Sub Total: <input type="text" id="sub_total" name="sub_total" readonly="readonly" /><br>
Includes GST: <input type="text" id="gst_total" name="gst_total" readonly="readonly" /><br>
Total: <input type="text" id="g_total" name="g_total" readonly="readonly" />
JS
function total(){
var total_value = 0;
var all_others = document.getElementsByTagName("input");
for(var i=0; i<all_others.length; i++){
if(all_others[i].type!="text" || all_others[i].name!="others"){
continue;
}
total_value += parseFloat(all_others[i].value);
}
document.getElementById("units_total").value = (total_value).toFixed(1);
document.getElementById("sub_total").value = ((total_value) *100).toFixed(2);
document.getElementById("g_total").value = (((total_value * 10/100) + total_value) * 100).toFixed(2);
document.getElementById("gst_total").value = ((total_value * 10/100) * 100).toFixed(2);
}
Firstly, to get your function to execute on window load, wrap it in a load event:
window.onload = function() {
total();
}
Secondly, to get it to figure in discount, you just need to modify your variable a few times, but then when adding them together, make sure you parse them with .parseFloat():
if (document.getElementById('discount').value != '') {
var discount = document.getElementById('discount').value;
}
else {
var discount = 0;
}
var sub_total = (((total_value) * 100).toFixed(2) - discount).toFixed(2);
var gst = ((total_value * 10 / 100) * 100).toFixed(2);
document.getElementById("sub_total").value = sub_total;
document.getElementById("gst_total").value = gst;
document.getElementById("g_total").value = (parseFloat(sub_total) + parseFloat(gst)).toFixed(2);
DEMO
First of all, I suggest you to perform validation and computations both server side and client side. The first ensures security while the second improves the responsiveness of the UI.
Said that, you'd better introduce several support variables and perform computation on them. You should get the value from the elements you are interested into using getElementById and store it in variables.
Then you should perform computation on that variables and finally place the results in the elements you want to use to display them to the user.
To perform the operation when the page loads have a look at this.

Categories

Resources