Numeric computations are not performing correctly - javascript

I've got a form which utilizes some checkbox inputs with fixed values and a text 'number' input which should be calculated against an hourly rate.
The idea is that we can select pre-set values and display the total including the number of billable hours times the hourly rate.
<script>
$( document ).ready(function() {
var sum = 0;
var origsum = 0;
var newsum = 0;
var tax = 0.06;
var hourly = 250;
var tothours = 0;
$('.cost').click(function() {
var total = parseInt($('#total').val());
if($(this).is(':checked')) {
sum = total + parseInt($(this).val());
} else {
sum = total - parseInt($(this).val());
}
$('#total').val(sum);
});
$('.tax').click(function() {
var total = parseInt($('#total').val());
if($(this).is(':checked')) {
origsum = sum;
newsum = total + (tax * parseInt(sum));
} else {
newsum = total - (tax * parseInt(sum));
}
$('#total').val(newsum);
});
var prevCount = 0;
var newCount = 0;
$(document).on('keyup mouseup', '.rate', function() {
newCount = parseInt($('.rate').val());
total = parseInt($('#total').val());
if(newCount > prevCount) {
$('.cost').each(function() {
if($(this).is(':checked')) {
sum = total + hourly;
$('#total').val(sum);
return false;
}
else {
$('#total').val($('.rate').val() * hourly);
}
});
}
else {
$('.cost').each(function() {
if($(this).is(':checked')) {
sum = total - hourly;
$('#total').val(sum);
return false;
}
else {
$('#total').val($('.rate').val() * hourly);
}
});
}
prevCount = parseInt($('.rate').val());
});
});
</script>
The best way to explain it is by example, so I created this fiddle which includes the script and html:
https://jsfiddle.net/dfkw4ggt/4/
As you'll see when you poke around (thanks in advance, btw!), it's all fairly well working until we start adding/clicking in the text/numeric field.
Any advice and/or pointers would be greatly appreciated as I've about exhausted my researching this and would love to get it working.

Here's my take, and my opinion.
I think you should have a Sub-Total, Total, and Tax. (You could still hide these fields from the end users and only show the "Total")
You can also simplify your code a bit to make it easier to find errors.
Take a look at this fork of your fiddle, where I changed your JS code and added sub/tax/total. Notice how, if there are errors in the calculations, it will be easier to find now.
The JS:
var taxRate = 0.06;
var hourly = 250;
// we really only need one event listener for the whole page
$(document).on("change", "input", updateTotal);
function updateTotal() {
var runningTotal = 0;
// find all checked cost fields
$(".cost:checked").each(function(){
runningTotal += parseInt($(this).val());
});
var billableAmount = parseInt($(".rate").val()) * hourly;
runningTotal += billableAmount;
$("#subtotal").val(runningTotal);
var tax;
if ($(".tax").prop("checked")) {
tax = runningTotal * taxRate;
} else {
tax = 0;
}
$("#taxAmt").val(tax);
$("#total").val( runningTotal + tax );
}

Related

I want to fixed the decimal places of the textbox value

The function below also calculates the sum on run time. The txtRate is the textbox to be processed for the decimal fix.
$(function() {
$("[id*=txtRate]").val("0");
});
$("body").on("change", "[id*=txtRate]", function() {
var rate = parseFloat($.trim($(this).val()));
if (isNaN(rate)) {
rate = 0;
}
//Update the Rate TextBox.
$(this).val(rate);
//Calculate and update Row Total.
var row = $(this).closest("tr");
$("[id*=lblTotal]", row).html(parseFloat($(".quantity", row).html()) * parseFloat($(this).val()));
//Calculate and update Grand Total.
var grandTotal = 0;
$("[id*=lblTotal]").each(function() {
grandTotal = grandTotal + parseFloat($(this).html());
});
$("[id*=lblGrandTotal]").html(grandTotal.toString());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

Store and code values of range sliders as embedded data field in Qualtrics

I would like to store the values of several range sliders, code them as "0"/"1", add them up and store the sum in an embedded data field in Qualtrics. However, with my code below, it only codes and stores the value of the last moved slider.
How can I circumvent that and store the values of all sliders?
Qualtrics.SurveyEngine.addOnload(function()
{
var sliders = document.getElementsByClassName('more-left');
var len = sliders.length;
for ( var i = 0; i < len; i++ ) {
var slider = sliders[i];
slider.addEventListener('change', function() {
updateValue(this);
});
updateValue(slider);
}
function updateValue(slider) {
var id = slider.id;
if (!id) {
return;
}
var val = document.getElementById(id + '_value');
if (val) {
val.innerHTML = slider.value;
}
var question_text = slider.value
if (question_text == 50) {
score = 1;
}
else {
score = 0;
}
Qualtrics.SurveyEngine.setEmbeddedData("Output",score);}});
Thank you!

jQuery sum add all TD values in table on click of a button

I have a form with few fields which does a small calculation. Once all the dropdowns are populated and clicked on Add Button It will display time for specific task. Likewise If you do the calculation couple of times the data will display in the table. and all values in time column will sum add together and display in another row. I have already implemented that. But it keeps adding to the existing value each time.
Refer to the image:
JS Fiddle
$(document).ready(function () {
$('#calculate').click(function () {
let tr = $("<tr/>").appendTo("#data tbody");
$('#calc input, #calc select').each( function (index) {
var input = $(this);
$(tr).append('<td class=row-'+ $(input).attr("id") + '>' + $(input).val() + '</td>');
});
const componentFactor = $(tr).children(".row-component").text();
const units = $(tr).children(".row-units").text();
const total = componentFactor*units;
$(tr).append('<td>' + total + '</td>');
$("#calc")[0].reset();
$("#total").html(sumColumn(5));
function sumColumn(index) {
var total = 0;
$("td:nth-child(" + index + ")").each(function() {
total += parseInt($(this).text(), 10) || 0;
});
return total;
}
});
});
The problem is that you are including the total line in your sum function. The .each correctly hits every TD element at the right index, but it is also including the first line.
If you modify your sum function like so, it works.
function sumColumn(index) {
var total = 0;
$("td:nth-child(" + index + ")").each(function() {
if(this.id !== 'total') {
total += parseInt($(this).text(), 10) || 0;
}
});
return total;
}
Same conclusion, you are adding total in your code; you can also use the following option:
function sumColumn(index) {
var total = 0;
$("tr> td:nth-child(" + index + ")").not(':first').each(function(i,item) {
total += parseInt($(this).text(), 10) || 0;
});
return total;
}
You can see it working here: JSFiddle demo

jquery - checkbox oncheck total will be updated

I was trying to develop a checkbox using jQuery ..where oncheck total will be updated but when i uncheck it will be back as it is.. Here total updated with oncheck but it don't get back to total amount when i uncheck it .what could be possible error..anyone help please?
$('#vat').on('click',function(e){
var vat = document.getElementById("vat").value;
var total = document.getElementById("total").value;
var sum = +total + +vat;
document.getElementById("total").value = sum;
});
Assume #vat is your input id
1- You need to use change instead of click for radio and checkbox inputs
2- check if checked or not by using this.checked
$('#vat').on('change',function(e){
var sum = 0;
var vat = document.getElementById("vat").value;
var total = document.getElementById("total").value;
if(this.checked === true){
sum = total + vat;
}else{
sum = total - vat;
}
document.getElementById("total").value = sum;
});
And while you're using and tagged jquery
$('#vat').on('change',function(e){
var sum = 0;
var vat = parseInt($(this).val());
var total = parseInt($("#total").val());
if(this.checked === true){
sum = total + vat;
}else{
sum = total - vat;
}
$("#total").val(sum);
});

JS function that calculates products qty and options additional taxes

I have this complicated JS function that must calculate the sum of product single price * qty and if there are available options for the product and if the available options have extra tax it has to be added also to the total.
function update_amounts() {
var sum = 0.0;
$('#basketorder > tbody > .product').each(function () {
var qty = $(this).find('.qty option:selected').val();
var selectedoptaddtax = 0.0;
$('.selectedoptionselect option:selected').each(function () {
var selectedoptaddtax = $(this).attr('price');
})
var price = $(this).find('.price').val();
var amount = ((qty * price) + selectedoptaddtax);
sum += amount;
$(this).find('.amount').text('' + amount);
});
$('.total').text(sum);
}
I have prepared jsfiddle here
In the example I have only 1 product in the basket, but the function must calculate correct if more that 1 product in the basket.
$(document).ready(function () {
update_amounts();
$('.qty').change(function () {
update_amounts();
});
$('.selectedoptionselect').change(function () {
update_amounts();
});
});
You need to add selected option prices.
Code
$(document).ready(function () {
$('.selectedoptionselect, .qty').change(function () {
update_amounts();
}).change();
});
function update_amounts() {
var sum = 0.0;
$('#basketorder > tbody > .product').each(function () {
var qty = $(this).find('.qty').val();
var selectedoptaddtax = 0.0;
//Use find here
$(this).find('.selectedoptionselect option:selected').each(function () {
selectedoptaddtax += +$(this).attr('price'); // You need to add price
})
var price = $(this).find('.price').val();
var amount = (qty * price) + (qty * selectedoptaddtax); //Changes here
sum += amount;
$(this).find('.amount').text('' + amount);
});
$('.total').text(sum);
}
DEMO

Categories