How to add up values of checkboxes in real time using JQuery? - javascript

Should be easy, but this code isn't working for me:
$("#checkboxdiv input:checkbox").change(function() {
var total = 0;
$('#checkboxdiv input:checkbox:checked').each(function() {
total += parseInt(this.value, 10);
});
$('#totalsdiv').text(total);
});
The checkboxes to consider are all in the #checkbox div, and I'm trying to fill in the div with the total amount.
Thanks.

As the code is fine and works, it's probable there is an unrelated error elsewhere.
You should use the developer tools to debug and hunt it.

You could try to listen for the click event on the CheckBox, instead of the change event.

Without knowing your problem I'll guess at this
$("#checkboxdiv input:checkbox").change(function() {
var total = 0;
$('#checkboxdiv input:checkbox:checked').each(function() {
total += parseInt($(this).val(), 10);
});
$('#totalsdiv').text(total);
});

Related

Pass var and refresh Div on blur

I have the following code, the alert works fine. the div refreshes fine, the var is not returned what am I missing, thanks
$('.cap_per_day').blur(function () {
var sum = 0;
var remaining = 0;
$('.cap_per_day').each(function() {
if ($(this).val() != "") {
sum += parseFloat($(this).val());
remaining = total - sum;
}
});
//alert('Total Remaining '+ remaining);
$(document.getElementById('div.alert-div')).innerHTML = remaining;
$("div.alert-div").fadeIn(300).delay(2000).fadeOut(400);
});
It's not clear exactly what the problem you're trying to solve is, however from your code sample I can tell you that a jQuery object doesn't have an innerHTML property, and the 'id' selector looks more like a class. Try this instead:
$('div.alert-div').html(remaining);

Checkbox checked add to cart

So I'm having some issues with my cart. Some jQuery issues and I was wondering if someone could point me in the right direction.
Thing is that I'm trying to make the cart more dynamic, if you check in a checkbox the item gets added to the cart and the total price and discount for that item is shown too.
Just having trouble with the checkbox part.
$(document).ready(function($){
$('#cart_listing .quantity').change(function (event) {
$quan = $(this);
console.log($quan.parent().next()[0]);
$quan.parent().next().find('.price').text(function () {
return $quan.val() * parseInt($(this).attr('data-val'), 10) + ' €';
});
var total = 0;
$('#cart_listing .price').each(function(k, v){
total += parseFloat($(v).text(), 10);
});
$('#cart_listing .faster').text(function () {
faster = parseInt($(this).attr('data-val'), 10);
return $(this).attr('data-val' + ' €');
});
var discount_pct = parseInt($("#cart_listing .discount").data("val"), 10);
var discount = -(total * discount_pct/100);
$('#cart_listing .discounted').text('-' + -discount + ' €');
$('#cart_listing #total').text(total + discount + faster + ' €')
});
});
jsFiddle: http://jsfiddle.net/ooh43u6t/
I don't understand your question correctly, but I think you want to add the value for the checkbox when checked using jQuery.
$('input[type=checkbox]').click(function(){
if($(this).is(':checked')){ //use this to see if the checkbox is checked or not
//do something...
}
});
I don't know if you wanted something like this. If not, can you clarify more? Thanks!
Edit:
So, you basically use the same thing, something like this perhaps,
if($(this).is(':checked')){
console.log($(this).parent('td').siblings('td').html()); // check this, you'll have the item name. (the first td)
console.log($(this).attr('data-val')); // this will have the value on the "data-val" attribute on your checkbox
}
So, now you have the name of the product (1st log) and the price (2nd log).
Now keep in mind that this would work only if the format is going to be consistent, and also instead of doing a generic input[type=checkbox], you might want to give all the product checkboxes a unique class, so it doesn't interfere with other checkboxes you might have. Hope this helps. If not, I'd be happy to answer some more. Thanks!

How to divide sum by 2 if checkbox checked? javascript/html

Like written in the Title. I am trying to get the sum from some fields - this is working fine already. But I want to add a function that if the check box is checked before and I press the "Calculate" Button the sum should be divided / 2 automatically. I don't have the code I already have in the moment but if its needed I will upload later. But for now maybe its some easy thing and very general. Maybe someone can give some example already. kind regards
Since you did not provide any markup, you should do something like this, but adapted to your code:
var sum = calculateSum();
if ($("#checkbox").is(':checked')) sum = sum/2;
$('#calculateButton').on('click', function(){
// do summation and assign it to sum variable
var sum = sumCalculation();
if ($('#checkbox').is(':checked'))
{
sum = sum/2;
}
});
You may try:
$("#checkbox").change(function(){
if($(this).is(':checked')){
// do the division
}
});
Assuming your checkbox would have id="checkbox"
var chksum = document.getElementById('u r checkbox ID').checked;
if(chksum=="true")
{
sum=sum/2;
}
Try this. Note let the id of checkbox is #checkbox
var sum = 10;
$("#checkbox").change(function(){
if($(this).is(':checked')){
sum /=2;
}
alert(sum);
});

Getting NaN during calculation

I am trying to calculate the total of a selection of CDs in addition of P&P. The code I'm using is coming to a total of NaN?
Very confused here. what am I doing wrong?
function calculateTotal() {
var Collection method = document.getElementById('collection').value +
var select CDs = document.getElementById('selectCD').value;
var total = document.getElementById('total');
total.value = 'collection'(total) + 'selectCD'(total);
}
Here is a JSFiddle with the full code.
In your fiddle collection and selectCD are divs (not inputfields) containing inputfields. You can't do divElm.value.
Then the php-code in your fiddle would normally be able to output more then one cd, so you'd need to add the totals of the selected cd's to.
The minimum changes needed to get your code working are:
function calculateTotal(){
var coll = document.getElementsByName('deliveryType'),
cds = document.getElementsByName('cd[]'),
cdTot = 0,
L = coll.length;
while(L--){if(coll[L].checked){ //get shipping costs
coll=Number(coll[L].getAttribute('title')); break;
} }
L=cds.length;
while(L--){if(cds[L].checked){ //add total prices
cdTot += Number(cds[L].getAttribute('title'));
} }
// output total
document.getElementById('total').value = coll + cdTot;
}
Also you'd want to set some more triggers to function calculateTotal (from the shipping costs and selected cd's; this way, if they change, the total-field will update to).
See this working fiddle with these changes (and some other fixes) based on your fiddle so you can get motivated seeing it (calculation) in action.
However I do hope this is for a school-question and not for a live webshop. I would re-think my strategy as I think you are currently working your way to a big security hole.
Good luck!

Adding up a load of input boxes

This may have been answered before, but I cannot find a solution that works.
I need to add the subtotal input boxes up and output them as a grandTotal. Sounds simple, and I thought it would be, but for some reason I cannot get it to function properly.
To save time I have created a jsFiddle - http://jsfiddle.net/wgrills/hKxgU/4/
Edit: Sorry to be poor at posting the question.
I missed out most of the items because I wanted to speed the jsfiddle up. I have updated the jsFiddle - http://jsfiddle.net/wgrills/hKxgU/7/.
If you click on the + or - buttons the subtotal changes, that is all good. But I can't get the #grandTotal input to update. The problem appears to be with the:
var grandTotal = 0;
$(".subtotal").each(function() {
$(this).css("border-color","#f00");
grandTotal += $(this).val.split("£")[1];
});
$("#grandTotal").val("£" + grandTotal);
alert(grandTotal);
part of the js. Note the css border change and the alert is just there for me to make sure the script is working.
The code is all early days, this is just a quick mock up.
You gave two problems, very easy to solve!
You are correct that the piece above that you posted is part of the problem. In particular the line:
grandTotal += $(this).val.split("£")[1];
You missed the () after val, so the code WOULD have broken here, because it doesn't know what .val. is.
Also, the code you posted was after a return false; this effectively tells the function is has finished, don't bother doing anything after that line.
However, as you need that section of code in both functions (clicks) its worth wrapping it in a function of its own:
function updateGrandTotal() {
var grandTotal = 0;
$(".subtotal").each(function() {
$(this).css("border-color", "#f00");
grandTotal += parseFloat($(this).val().split("£")[1]);
});
$("#grandTotal").val("£" + grandTotal);
alert(grandTotal);
}
And calling it just before you inform the function its finished:
updateGrandTotal();
return false;
See it partially working here
However, while this will work on the plus of an item, you have another problem, when you are minusing an item, and the box gets to zero, instead of setting £0.00 you set it to 0, hence when it try's to split on the "£" it can't. To combat this simply copy the bit where you turn your price value into a price from the plus function into the minus function:
Replace:
newprice = price * x;
$('#' + update).val(x);
$('#' + update + '_subtotal').val(newprice);
With the working version:
newprice = (price * x) / 100;
newprice = newprice.toFixed(2);
newprice = '£' + newprice;
$('#' + update).val(x);
$('#' + update + '_subtotal').val(newprice);
See it fully working here
Your problem is with the following line:
grandTotal += $(this).val.split("£")[1];
val is a function, not a property on the returned object. You want the following instead:
grandTotal += $(this).val().split("£")[1];
Also in your fiddle you have a return false; in the middle of your function, which lies above the code you're calling val incorrectly on. Remove that return as well.

Categories