Javascript keep decimal place - javascript

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.

Related

Adding the sum of checkboxes appending instead of adding

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))

JavaScript calculation returns NaN

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')

Return total of a GTM JavaScript variable (array) in another GTM JavaScript variable

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"; }

if statement not working properly in jquery

I have two arrays: arr and myArraycode. Both have some values retrieved from a database. The values of myArraycode are displayed in select on each row. Now I need to disable all rows which have a value not appearing in the arr array.
For example,
arr =["abc","cde"];
myArraycode=["sample","abc","cde"];
I have three table rows which have sample in one row, abc in another and cde in a third. Now i need to disable the row with sample because sample is not in the array arr.
I have tried the following code:
var kt = 0;
var kts = 0;
var sk=0;
var sv =0;
while(kt < myArraycode.length)
{
if($.inArray(myArraycode[kt],arr) === -1 )
{
$("#table tr").find('td').find("select:contains("+myArraycode[kt]+")").closest('tr').find('input[type=text]').attr("disabled","disabled");;
$("#table tr").find('td').find("select:contains("+myArraycode[kt]+")").closest('tr').find('select').attr("disabled","disabled");;
}
kt++;
}
Please help me to solve the problem.
Demo
arr =["abc","cde"];
myArraycode=["sample","abc","cde"];
for(var i=0; i < myArraycode.length; i++)
{
if($.inArray(myArraycode[i],arr) === -1 )
{
$('option[selected="selected"]:contains("'+myArraycode[i]+'")').parent().attr('disabled','disabled');
}
}
I've corrected some of the syntax errors, but this should do the trick for you
For performance reasons you could also either use a decremental for loop or save the array.length value in a variable so the loop doesn't need to recalculate the value every run
I have updated your answer in jsfiddle
Note that the HTML requires the selected attribute for this to work
<option value="sample" selected="selected">sample</option>
I tried the following code to disable select box having selected value as sample
$( document ).ready(function(e){
arr =["abc","cde"];
myArraycode=["sample","abc","cde"];
for(var i=0; i < myArraycode.length; i++)
{
if($.inArray(myArraycode[i],arr) === -1 )
{
$("select").each(function(){
if($(this).val() == myArraycode[i])
{
$(this).closest('tr').find('select').attr('disabled','disabled');
}
});
}
}
});
Demo

Recursive Javascript function using callback not working

I am trying to fix a problem with my recursive function JS using a call back. I just want to update the HTML of 3 div using according to an index. Please find the code below
<div id="try0">50</div>
<div id="try1">50</div>
<div id="try2">50</div>
function getNumberOfAnswers(questionID, callback)
{
var value = i*10;
callback( value.toString());
}
var i=0;
getNumberOfAnswers(i, function callFunc(ratio){
var itemToChg = 'try'+i;
document.getElementById(itemToChg).innerHTML = ratio;
if(i<3){
i++;
getNumberOfAnswers(i,callFunc(ratio));
}
});
I didn't put any tags on the code above to simplify but I made a JSfiddle with it. http://jsfiddle.net/cyrilGa/zmtQ8/ . On the third line from the end, I tried to write getNumberOfAnswers(i,ratio); but it didn't work.
Can somebody help me with this
Cheers
The line:
var value = i*10;
should be
var value = questionID * 10;
And I think
getNumberOfAnswers(i,callFunc(i));
Should be:
getNumberOfAnswers(i,callFunc);
Do not use recursion for this, it is silly.
for ( var i = 0; i < 3; i++ ) {
document.getElementById('try' + i).innerHTML = i * 10;
}
Is this what you want?
You need to replace the recursive callFunc(ratio); at the bottom to callFunc(i); because the argument ratio is still equal to 0 while you increment i. Everything else is fine.

Categories

Resources