I'm attempting to display a subtotal each time a customer enters a quantity. However, when I loop through my inputs, I get a NaN as the total. I believe it may be the way I'm declaring the subtotal variable in my script, but I haven't come across this before:
$('.item-qty input').bind('keyup', function(){
var subtotal = 0.0;
$('.item-qty input').each(function(){
var class = $(this).attr('id');
var qty = $(this).val();
var price = $('.'+class).html();
price = parseFloat(price);
qty = parseInt(qty);
subtotal = subtotal + (price * qty);
});
$('.subtotal input').val(subtotal);
});
parseFloat and parseInt can return NaN if the first character of the string cannot be converted to a number.
So, I would safeguard against it like this (NaN is a falsy value):
price = parseFloat(price) || 0;
qty = parseInt(qty, 10) || 0;
Arithmetic operations on numbers with the value NaN almost always result in NaN (NaN + 5 will result in NaN.) That means, if only one of the input cannot be parsed by parseFloat or parseInt, your current code would end up calculating NaN for the subtotal.
It's already been mentioned in the comments (by Felix mostly) but I think it's worth the emphasis as these are important concerns:
Always pass the radix argument to the parseInt function;
Do not use class for variable names: It's a reserved (not used, but reserved) keyword;
Don't expect the subtotal to be perfectly accurate unless you do your calculations in cents.
Related
There are two fields - faceValue fv2 and askingPrice num2 - and askingPrice can't be less than faceValue.
The check is almost working, but with a face value of 10.00, the alert only triggers when the asking price is 1.00 (9.00, 8.00 etc etc don't trigger it). However, when fv2 reloads into the form it's correct - 10.00.
How to fix this issue? here's the code
// new askingPrice comparison
var fv2 = parseFloat($('.ticketFaceValue').val()).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
var num2 = parseFloat($(this).val()).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
if (num2 < fv2) {
alert('Sorry, your asking price can\'t be less than face value. Please change your asking price.');
$(this).val(fv2);
row.find('.askingPriceData').html(fv2);
recalculateFees();
}
// end new askingPrice comparison
Although you use parseFloat to convert the input string to a number type, you convert it back to string with toFixed, and so the comparison is character based, not by numerical value.
The thing you try to do with a replace (add thousands separators) can also be done with toLocaleString, but you need to take care to not to put that formatted string back into the input element, as it will not parse as a number. It is probably better to use separate variables for the numerical value and the formatted value. Maybe like this:
var fv2 = +$('.ticketFaceValue').val()
var num2 = +$(this).val();
var fv2Fmt =fv2.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
var num2Fmt =num2.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
if (num2 < fv2) {
alert('Sorry, your asking price can\'t be less than face value. Please change your asking price.');
$(this).val(fv2);
row.find('.askingPriceData').html(fv2Fmt);
recalculateFees();
}
toFixed() method returns string so you are comparing two strings. Try the below code.
var fv2_float = parseFloat($('.ticketFaceValue').val());
var num2_float = parseFloat($(this).val());
var fv2 = fv2_float.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
var num2 = num2_float.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
if (num2_float < fv2_float) {
// Do your staff
}
Or try below one, but this is not very efficient.
// Your code goes here
if (parseFloat(num2) < parseFloat(fv2)) {
// Do your staff
}
In Jquery, how do you take a variable and set a second variable with a decimal in front of the value of the first variable.
For example I have a variable that is set from a form input values. I named this variable subTotal. Now I want to take that variable and set another variable with a decimal in front of it so I can calculate a percentage by multiplying another input value.
So here is some of the code for example
var subTotal = self.calculateTotalFor(elems);
total += (quantity - 1) * NewVariable;
self.calculateTotalFor(elems); comes from the input on the form
NewVariable would be Subtotal with a decimal in front.
Try :
var subTotal = self.calculateTotalFor(elems), total = 0;
total += (quantity - 1) * NewVariable;
or
total += parseFloat((quantity - 1) * NewVariable);
Try this
var NewVariable = parseFloat("." + Subtotal);
This will take "." and your Subtotal value and perform a string
append
parseFloat will convert the string to a floating point number
i have a Invoice form and a jquery function.
In Invoice if i enter the quantity greater then the available quantity then i have to alert the user.
My problem is: Let the max quantity is 5, if i input data as 7 (single digit>max avail quantity) then my code is working fine. But if i enter two digigist number eg. 17(two digists>max avail quantity) then my alert box is not coming.
I mean onkeyup my function is working only with single digit.
How can i make it happening? Please help.
$('input[name="quantity"]').keyup(function()
{
//problem is here
var $tr = $(this).closest("tr");
var unitprice = $tr.find('input[name^="unitprice"]').val();
var q = $tr.find('input[name^="quantity"]').val();
var cq = $tr.find('input[name^="checkquantity"]').val();
if(q>cq)
{
alert("Error: Quantity value exceeds then available quantity..Max Quantity is "+cq);
//this works fine only if single digit is entered in textbox quantity
}
//----below are some other stuffs -these are working fine
$tr.find('input[name^="sprice"]').val($(this).val() * unitprice);
var totalPrice = 0;
$('input[name="sprice"]').each(function()
{
totalPrice += parseFloat(this.value);
$('[name=subtotal]').val(totalPrice);
});
});
--------------
------------
// Form containing the above textboxes
<input type="submit" id="submitbtnId" value="Save"/>`
q > cq is comparing 2 strings, which is not what you want. You're trying to compare the numerical value of those strings.
Use this instead:
if ( +q > +cq)
{
// alert your error
}
Note that by prefixing the variables with the + sign, you're converting them to a number.
Better yet, convert them to a number as soon as you get the values:
var $tr = $(this).closest("tr");
var unitprice = +$tr.find('input[name^="unitprice"]').val();
var q = +$tr.find('input[name^="quantity"]').val();
var cq = +$tr.find('input[name^="checkquantity"]').val();
if ( q > cq )
{
alert("Error: Quantity value exceeds then available quantity..Max Quantity is " + cq);
}
You need to use parseInt() to ensure you are comparing integers, not strings:
if (parseInt(q, 10) > parseInt(cq, 10)) {
/* Rest of your code */
}
Your values are compared as string. If you want to compare Numbers, either use:
parseInt() or parseFloat()
or
[..].val() * 1, but this will return 'NaN' if its no digit, while parseInt() and parseFloat() will return 0
Im using the following method to add up text boxes. I have tried changing multiple things and cant seem to multiply two text box values! essential I want 2 text box that values are multiplied and displayed in a third text box. I want this value to be fluid aka change when the number changes! I was using this code because i may be multiplying more then one thing but if this is too much of a hassle i will live with just multiplying two at a time
The code im using to add is
<!--adding script #-->
<script>
$(document).ready(function(){
calculateSum();
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".txt").each(function() {
$(this).keyup(function(){
calculateSum();
});
});
});
function calculateSum() {
var sum = 0;
$("#sum").val(sum.toFixed(2));
//iterate through each textboxes and add the values
$(".txt").each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sum").html(sum.toFixed(2));
var total = document.getElementById("subtotal").value == "";
var total = document.getElementById("subtotal").value = sum;
}
<!--END adding script #-->
I tried setting the last line to
var times1 = document.getElementById(subtotal);
var times2 = document.getElementById(tax);
var equal = times1.value * times2.value;
and then changing var total1 = document.getElementById("total1").value = sum9; to var total1 = document.getElementById("total1").value = equal;
The text boxes id are subtotal and tax the box im trying to update is total1.
Thanks alot!
On every keyup, instead of getting all values and adding them explicitly, it is better to deduct the previous value of the corresponding input and add the current updated value to sum..
Also, if subtotal is correctly calculated, then the multipication operation what ever you have done should work correctly..
Please find the following jsfiddle where the sum is calculated as explained above along with multiplying the tax..
http://jsfiddle.net/tgvrs_santhosh/77uxK/1/
Let me know if you still face the issue..
Instead of this
if(!isNaN(this.value) && this.value.length!=0) {
I think a regular expression may work better because you are using string values
if (/^([-]?((\d+)|(\d+\.\d+)|(\.\d+)))$/.test(this.value)) {
I haven't tested this regex, but you should be able to find a good regex to test for valid numbers if this one doesn't work for some reason. Also I noticed you have a == after that getElementById.
I'm not totally certain it matters, but you can do sum += (this.value * 1) instead of parseFloat.
update
Try this var equal = ($("#subtotal").val() * 1) * ($("#tax").val() * 1);
I found your question very confusing, but I think what you're trying to say is you want to add up all the .txt fields to get a sub-total, then multiply that sub-total by a tax rate to get a total. If so, then you already know the sub-total is a valid number due to the way you calculate it, so then:
var tax = +$("#tax").val(), // get tax and convert to a number
total = tax ? sum * tax : sum; // if tax is a non-zero number multiply
// otherwise just take the sum as is
If your tax field is not an input then use .text() instead of .val().
Your existing code is rather more complicated than it needs to be. You can do this:
$(document).ready(function(){
calculateSum();
// you don't need an .each() loop, you can bind a keyup handler
// to all elements in the jQuery object in one step, and you don't
// need the anonymous function since it does nothing but call calculateSum:
$(".txt").keyup(calculateSum);
});
function calculateSum() {
var sum = 0,
val;
//iterate through each textboxes and add the values
$(".txt").each(function() {
// you don't need to test for NaN: just attempt to convert this.value
// to a number with the unary plus operator and if the result is not
// a number the expression val = +this.value will be falsy
if(val = +this.value)
sum += val;
});
$("#sum").html(sum.toFixed(2));
var tax = +$("#tax").val();
$("#total1").html((tax ? sum * tax : sum).toFixed(2));
}
For some reason the unary plus operator used throughout my answer is not widely known, but I prefer it to parseFloat().
I am using the following code snippet to calculate a total price. This works great except #totalPrice on some occasions expands out to for example $267.9999999999. How do I reformat #totalPrice within this function to just round to two decimals as is standard in dealing with price.
function getTotalCost(inventory) {
if(inventory) {
getTotalParts(inventory);
getTotalMarkup(inventory);
}
var labor = $('#labor').val() * 1;
var totals = 0;
for(i in totalMarkup) {
totals += totalMarkup[i];
}
totalCost = totals+labor;
/*if(totals == 0) {
totalCost = 0;
}*/
$('#totalPrice').html(totalCost);
}
You can have:
$('#totalPrice').html(totalCost.toFixed(2));
See:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number/toFixed
Notice that toFixed method returns a formatted number, therefore converts the number to a string. It's not a problem here because html wants a string, but it's keep it in mind that in order to avoid concatenation of string when you expects sum of numbers. I believe you use $('#labor').val() * 1; for this very reason. However it's not necessary, it's better use method like parseFloat or the unary plus operator:
var labor = +$('#labor').val();
When working with javascript the floating points are always a bad. Best you can do is, round it up.
But in this case you can do
(totalCost).toFixed(2);
You can use Math.round function in JavaScript like this.
totalCost = Math.round(totalCost*100)/100;
$('#totalPrice').html(totalCost);