What i am trying to do in my form is, when a user clicks on certain checkboxes, the value (in float form) is added up to a sum, but the way my code is now it appends instead of adds.
This is my code:
<script>
$(document).ready(function() {
function updateSum() {
var total = "0.00";
$(".sum:checked").each(function(i, n) { total += parseFloat($(n).val()).toFixed(2); })
$("#total").val(total);
}
// run the update on every checkbox change and on startup
$("input.sum").change(updateSum);
updateSum();
})
</script>
When i check multiple boxes i get: 1.002.003.00 instead of: 6.00
my code looks right i cannot see what i have missed. Any advice on the issue would be appreciated.
Let's see a quick example how toFixed() behaves and how should you add floats in JavaScript if you have the original value as a string:
(function() {
var total = '0.00';
for (var i = 0; i < 5; i++) {
total = (parseFloat(total) + parseFloat(4.3)).toFixed(2);
}
console.log('total', {
total: total,
typeOfTotal: typeof(total)
});
})();
Based on the below example you can see that toFixed() returns a string so I suggest to modify to your code to the following in order to add numbers properly:
$(document).ready(function() {
function updateSum() {
var total = "0.00";
$(".sum:checked").each(function(i, n) {
let sum = parseFloat(total) + parseFloat($(n).val());
total = sum.toFixed(2);
});
$("#total").val(total);
}
// run the update on every checkbox change and on startup
$("input.sum").change(updateSum);
updateSum();
});
You can read further about Number.prototype.toFixed() and parseFloat() here.
Change your total= '0.00' to number( total = 0.00 ) instead of string.
toFixed returns string not numbers
let x = 1.22
console.log(typeof (1.22).toFixed(2))
Related
I am doing an exercise on JS Hero website:
Write a function add that takes a string with a summation task and returns its result as a number. A finite number of natural numbers should be added. The summation task is a string of the form '1+19+...+281'.
Example: add('7+12+100') should return 119.
The code I have written is as follows:
function add (string) {
let partsArray = string.split("+");
let added = parseInt(partsArray[0]);
for (let i=0; i<=partsArray.length; i++) {
added = added + parseInt(partsArray[i]);
}
return added;
}
It returns NaN. Any ideas how to solve this one?
You were going out of bounds on your array. Also you should just initialize the added to 0 as you start looking at the array from index 0. Note I added some console.logs to give you an idea of how you might debug something like this.
function add (string) {
let partsArray = string.split("+");
console.log("parts", partsArray);
let added = 0;
for (let i=0; i<partsArray.length; i++) {
console.log("i",parseInt(partsArray[i]));
added += parseInt(partsArray[i]);
}
return added;
}
If you add the <= back and run the code with the console.logs you will see in console the following. Note with the <= you have 4 indexes rather than the expected 3. This is because the size is 3 but the array is indexed from zero. When you use < you get the expected answer.
You could also use the reduce method:
function add(string) {
return string.split('+').reduce((accumulator, currentValue) => accumulator +
parseInt(currentValue, 10),0)
}
If you still want to start with the first index ..you can do it like below
function add (string) {
let partsArray = string.split("+");
let added = parseInt(partsArray[0]);
for (let i=1; i<partsArray.length; i++) {
added += parseInt(partsArray[i]);
}
return added;
}
function add(input) {
let myinput = input.split("+") //split your value
let sum = 0;
for (let i = 0; i < myinput.length; i++) {
sum = sum + +myinput[i]; //use + for identify the number value
}
return sum;
}
The simplest possible answer is:
function add(str){
return eval(str)
}
I want to find total sum of passing the field values in array. If the field is for discount then perform minus else plus. For some reason I'm getting nan.
Here is my script code
<script>
var partial_cost = $('#bill_amount:disabled').val();
var fine = +$('#fine').val();
var discount = +$('#discount').val();
var other_cost = +$('#other_cost').val();
var total_cost = +$('#total').val();
var chargeAble = [
partial_cost,
fine,
discount,
other_cost
];
$.each(chargeAble, function (chargeIndex, charge) {
charge.blur(function () {
var amount = 0;
for(charge in chargeAble)
if(chargeAble[charge].attr('id') == 'discount')
amount -= (chargeAble[charge].val());
else
amount += (chargeAble[charge].val());
total_cost.val(amount);
});
});
</script>
The code is using a combination of .each() AND a for-in loop... and strangely the callback from a blur() function? It can be simplified like this:
var amount = 0;
$('#bill_amount:disabled, #fine, #discount, #other_cost')
.blur()
.each(function() {
var sign = this.id === 'discount' ? -1 : 1;
amount += parseFloat($(this).val()) * sign;
});
$('#total').val(amount);
Update:
Oh, you want the total to update on blur... try this code:
var $values = $('#bill_amount:disabled, #fine, #discount, #other_cost');
$values.on('blur', function() {
var amount = 0;
$values.each(function(){
var sign = this.id === 'discount' ? -1 : 1;
amount += parseFloat($(this).val()) * sign;
});
$('#total').val(amount);
});
I can see stuff like this all around:
var fine = +$('#fine');
The jQuery() method returns jQuery objects, not numbers or even strings. Forcing a number cast will thus return NaN.
You need to first grab the text inside and than parse numbers of out it. How to do it depends on how your HTML is structured but in general:
In form fields you can normally use .val()
In most other tags you can use .text()
Make sure that all values are interpreted as numbers by JavaScript. Otherwise it will try to calculate some odd result from a string, which might get interpreted as something else than the a decimal number (hex, octa, ...).
You array holds numbers and you act like they are strings
var chargeAble = [ //this holds values
partial_cost,
fine,
discount,
other_cost
];
and in the loop you are using it for an id???
chargeAble[charge].attr('id')
This is my very first question on this website, I am curious if someone could help me out. In Google Tag Manager I tried to set up a custom JavaScript variable with some jQuery that should return the total amount of all product prices within a specific array.
In the code below I return all product prices within an Enhanced Ecommerce dataLayer. In GTM, I have called this variable "{{product price}}".
function() {
var itemsInC = {{ecommerce.checkout.products}};
itemsincart = [];
for (var i = 0;i < itemsInC.length;i++) {
priceincart.push(itemsInC[i].price);
}
return priceincart;
}
The code above actually works and for example returns a value like: ['9.99', '21.95', '34.99'].
In the second piece of code I try to sum up the total of all returned values in the GTM variable "{{product price}}". However, the code below doesn't work properly. How could I return the total value of the script above in the script below?
This is what I created so far:
function() {
var total = $("{{product price}}").each(function() {
0 += parseInt($(this).val(), 10);
}
return total;
}
Thanks in advance!
Kind regards,
Assuming that you're using the exact code as you've got above, you've got a few syntax errors.
you don't need to wrap GTM variables in quotes
don't use parseInt because that just returns an integer. Use "Number" instead.
you left out a bracket
So you should probably use something like this:
function(){
var total = 0;
$({{product price}}).each(function(){
total += Number(this);
})
return total;
}
I don't know if it is normal to post an answer to my own question but I solved the issue above with the following code:
function() { var total = 0; for (var i = 0; i < {{product price}}.length; i++)
{ total += {{product price}}[i] << 0; } return total + ".00"; }
I'm relatively new to javascript/jQuery and I'm having trouble getting my expected outcome. I would like the total to be shown even if only one input has a value, otherwise I want 0 to be shown. However right now it requires all 3 values to be input before it will show the sum. It will not simply add the next input onto the total as I type into an input. I can imagine a series of lengthy conditional statements that would cross check each input for .length and return the total based on each input. Surely there has to be an easier/cleaner way. If this were java I would use total += (variable) and it would total them as I went. That doesn't seem to work here.
$('#invoice_labor, #invoice_materials, #invoice_other').keyup(function() {
if ($('#invoice_labor').length || $('#invoice_materials').length || $('#invoice_other').length ) {
updateTotal();
} else {
$('#invoice_total').html(0);
}
});
var updateTotal = function () {
var input1 = parseFloat($('#invoice_labor').val(), 2);
var input2 = parseFloat($('#invoice_materials').val(), 2);
var input3 = parseFloat($('#invoice_other').val(), 2);
var total = input1 + input2 + input3;
$('#invoice_total').html(total);
$("#invoice_total").html(parseFloat($("#invoice_total").html()).toFixed(2));
};
and here is the fiddle I was tinkering with.
So I want the total to change regardless of which field I type a number into. If it's only one, total that add that to the total variable and return it. If it's any combination of two then combine them and add them to the total. Thanks for the help.
Try
$('#invoice_labor, #invoice_materials, #invoice_other').keyup(function() {
updateTotal();
});
var updateTotal = function () {
var input1 = parseFloat($('#invoice_labor').val()) || 0;
var input2 = parseFloat($('#invoice_materials').val()) || 0;
var input3 = parseFloat($('#invoice_other').val()) || 0;
var total = input1 + input2 + input3;
$("#invoice_total").html(total.toFixed(2));
};
Demo: Fiddle
Your fiddle has few problesm
You were registering the input keyup event, in the body keyup handler which was wrong - it will cause the first keystroke not to be recognised and will fire multiple updatetotal calls in subsequent calls
If a field is empty parseFloat will return NaN which when added will result in NaN as the result
parseFloat takes only one argument
I am using the following code below to get the price from the attribute data-price which is assigned to radio buttons like so: data-price="25.00"
jQuery(document).ready(function($){
var frm = document.forms.myForm;
frm.onchange = function(e) {
var tot = 0;
for( var i = 0, l = frm.elements.length; i < l; i++ ) {
if( frm.elements[i].checked ) {
tot += parseFloat( frm.elements[i].getAttribute('data-price') );
}
}
document.getElementById('total').value = ( tot );
}
})
The problem I am getting is that when it dispalys it in the input box for the following example it would only show 25 I need it to say 25.00 is there a way around this?
tot.toFixed(2)
will give you the result.
And since you use jQuery, you could write more jQuery like code, just an example like below, just a suggestion:
$(function () {
$('form[name="myForm"]').change(function () {
var tot = 0;
$('input:checked', this).each(function () {
tot += parseFloat($(this).data('price'));
});
$('#total').val(tot.toFixed(2));
});
});
Try assigning tot.toFixed(2). Hope that helps!
Javascript won't show 25.00 if it is a number
console.log(25.00);
alert(25.00)
Both will show 25. It works only if there are non-zero digits after .
console.log(25.03);
So convert it to number for the calculations, and when showing in a text box use .toFixed(2) like others have suggested here.
document.getElementById('total').value = tot.toFixed(2);
toFixed converts it to string.