Sum Checkboxes without POSTING values - Javascript - javascript

I've had a look around but could find a definitve answer.
Basically, I have a Total, with an ID that im trying to automatically update once a checkbox is clicked.
p style="font-size: 1.2em; font-weight: bold;"><b>Total Cost:</b> £<input value="0.00" readonly="readonly" type="text" id="total"/></p>
The checkbox will have a simple value such as 1.50 or similar. (these are dynamic) so
<input name="product" value="<?php echo $count*0.50 ?>" type="checkbox">
This may be very simple! But im not that hands on with Javascript

Handling both checking and unchecking a box to update the sum for the input with a working jsbin example, also assuming you are using jquery.
var sum = 0;
var total = $('#total');
var cbox = $('.cbox');
$('.cbox').on('change', function() {
if ($(this).prop('checked')) {
sum += parseFloat($(this).val());
updateTotal();
} else {
sum -= parseFloat($(this).val());
updateTotal();
}
});
function updateTotal() {
total.val(sum);
}

$('input[type=checkbox]').change(function() {
var sum = 0;
$('input[type=checkbox]:checked').each(function() {
sum += Number($(this).val());
});
$('#total').val(sum);
});

IF you just want the checked "product" check boxes:
$('input[type="checkbox"][name="product"]').on('change', function() {
var newtotal = 0;
$('input[type="checkbox"][name="product"]').filter(":checked").each(function() {
newtotal = newtotal + Number($(this).val());
});
$('#total').val(newtotal);
});
Sample fiddle to play around with: https://jsfiddle.net/ovqkcqvn/

Related

start a function if another function is active and activate some checkboxes only - JQuery

i Have a function that I want to start only if another function is previously activated.
I have some CheckBoxes and I need to sum its values to get the total.
Only When a user has selected some of the CheckBoxes it must activate another checkbox with a discount.
I want that the discount checkbox get activated after the first selection because, if I don't do so, I could have a negative price.
Then (if it's possible) I want that the discount checkbox get deactivated is a user deselect all the previous CheckBoxes.
Is this possible?
Here's my script. I'm super new in JavaScript/jQuery so this might be a stupid question.
Thank you
$(document).on('change', getCheck);
function getCheck() {
var total= 0;
$('[type="checkbox"]:checked').not("#discount").each(function(i, el) {
//console.log($(this).not("#off").val());
var SumVehicle = parseFloat($(el).val());
total += SumVehicle;
//console.log(total);
//console.log(price_tot);
$('#rata').text(total +" €");
var finalprice = total;
//var Check = getCheck();
if(typeof(total) != "undefined" && total !== 0) {
$('[type="checkbox"]:checked').not(".sum").each(function(i, el) {
var Discount = parseFloat($(this).val());
finalprice = finalprice - Discount;
console.log(finalprice);
$('#rata').text(finalprice +" €");
});
};
});
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="sum" type="checkbox" name="vehicle1" value="1000"> I have a bike<br>
<input class="sum" type="checkbox" name="vehicle2" value="2000"> I have a car<br>
<br><br><br>
<input id="discount" type="checkbox" name="discount" value="200"> Discount<br>
<div id="rata">rata</div>
Replace your js code with this code. the error will be resolved.
$( document ).ready(function() {
$("input[type='checkbox']").on('change', getCheck);
});
function getCheck() {
var total= 0;
$('[type="checkbox"]:checked').not("#discount").each(function(i, el) {
console.log($(this).not("#off").val());
var SumVehicle = parseFloat($(el).val());
total += SumVehicle;
console.log(total);
//console.log(price_tot);
$('#rata').html(total +" €");
var finalprice = total;
var Check = function getCheck(){
if(typeof(Check) != "undefined" && Check !== null) {
$("#discount").toggle();
var Discount = parseFloat($(this).val());
finalprice -= Discount;
console.log(finalprice);
$('#rata').text(finalprice +" €");
};
};
});
};

Show an error when sum value is over 100

I'm trying to sum 100 on a variable ammount of input fields. I'm doing this using this Javascript:
$('.price').keyup(function () {
var sum = 0;
$('.price').each(function() {
sum += Number($(this).val());
});
$('#totalPrice').val(sum);
});
And it works! but now i need to do two things; if the user inputs a value different than a number, or if the total value is over 100, show a hidden div.
I'm really new Javascript, and i made this code but showing an error are major words for me now.
Thank you guys!
you might want something like this:
$('.price').keyup(function() {
var sum = 0;
$('.price').each(function() {
var inputVal = +$(this).val(); //each field's value converted to number using "+"
if (!isNaN(inputVal)) {
sum += inputVal;
$('.not-num-err').hide();
} else {
$('.not-num-err').show();
return false; //stop iteration
}
});
if (sum > 100) {
$('.over-hundred-err').show();
} else {
$('.over-hundred-err').hide();
}
$('#totalPrice').val(sum);
});
.hidden {
display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="price">
<input type="text" class="price">
<input type="text" class="price">
<div class="not-num-err hidden">You entered wrong number</div>
<div class="over-hundred-err hidden">Total is over 100!</div>
<p>
<label for="totalPrice">Total Price</label>
<input type="text" id="totalPrice">
check this link for more info on the unary plus (+) operator.
You can use this keyword inside it:
$('.price').keyup(function() {
if (isNaN(this.value) || (!isNaN(this.value) && this.value > 100)) {
// Do something.
alert("No!");
// Do not allow the function to proceed.
return false;
}
var sum = 0;
$('.price').each(function() {
sum += Number($(this).val());
});
$('#totalPrice').val(sum);
});
Working Fiddle: https://jsfiddle.net/ash06229/ydbjsx1z/
Try this:
$('.price').keyup(function () {
var sum = 0;
$('.price').each(function() {
if(sum <= 100)
{
$('.error').html("");
sum += Number($(this).val());
}
else {
$('.error').html("Sum is greater than 100").css("color","red");
}
});
$('#totalPrice').val(sum);
});

radioboxes only adds values on change, but doesn't subtract

I have 2 functions. One adds value from checkboxes and the other adds values from radioboxes to var tot.
The problem is that radiobox only adds value to var tot, but doesn't subtracts when unchecked.
I didn't have this problem until I scoped out the var tot, but it had to be done so that both functions could access it. Here is a code sample with the problem in action:
$(':checkbox:checked').prop('checked', false);
$('input[type="radio"]:checked').prop('checked', false);
$(document).ready(function() {
var tot = 0;
$('#usertotal').text('0 SEK')
$('input:checkbox').change(function() {
if (!$(this).is(':checked')) {
tot -= parseInt($(this).val());
} else {
tot += parseInt($(this).val());
}
$('#usertotal').text(tot + ' SEK')
});
$('input[type="radio"]').change(function() {
if ($(this).is(':checked')) {
tot += parseInt($(this).val());
} else if (!$(this).is(':checked')) {
tot -= parseInt($(this).val());
}
$('#usertotal').text(tot + ' SEK')
});
});
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<input type="radio" name="radioName" value="160 Yes">till 20
<input type="radio" name="radioName" class="someclass" value="5 Yes"> 20
<input type="checkbox" name="" value="29 Yes">BV
<div class="col-lg-4 col-mg-3 col-sm-12 col-xs-12 calculation-window">
Totalt: <span id="usertotal"></span>
</div>
jsfiddle: https://jsfiddle.net/ys1b9Lwv/12/
The issue seems to be that radio buttons don't fire the change event when they're unselected. Adding logging into the radio change event confirms this.
There are a few ways to solve this but I think the most elegant is to refactor the calculation of the total into a separate function, that checks the values of all the components involved in the sum / total.
I've come up with this solution:
var tot = 0;
$('#usertotal').text('0 SEK');
var update_tot = function () {
tot = 0; // reset
// sum of inputs that are checked
$('input:checkbox,input[type="radio"]').each(function(){
if ($(this).is(':checked'))
tot += parseInt($(this).val());
});
$('#usertotal').text(tot + ' SEK');
};
$('input:checkbox,input[type="radio"]').change(update_tot);
A cleaner rewrite of this could be:
var tot = 0;
$('#usertotal').text('0 SEK');
$('input:checkbox,input[type="radio"]').change(function () {
tot = 0; // reset
// sum of inputs that are checked
$('input:checkbox,input[type="radio"]')
.filter(':checked')
.each(function(){
tot += parseInt($(this).val());
});
$('#usertotal').text(tot + ' SEK');
});
We can't get de-select in radio box. so my solution is to fire deselect by ourself and identify already selected radio box. I am using class to achieve it.
$('input[type="radio"]').change(function() {
tot += parseInt($(this).val());
$(this).addClass("sel");
$('input[name="' + $(this).attr('name') + '"]').not($(this)).trigger('deselect');
$('#usertotal').text(tot + ' SEK')
});
$('input[type="radio"]').bind('deselect', function(){
if($(this).hasClass("sel"))
{
$(this).removeClass("sel");
tot -= parseInt($(this).val());
$('#usertotal').text(tot + ' SEK')
}});

Add and subtract values with jQuery

Need Help with following piece of jQuery code;
What I'm trying to do is;
add Amount into Total
when amount added Checkbox value get double
If checkbox state change, checkbox Updated value minus or add into Total accordingly
if Amount minus from Total, checkbox value change back to original
If checkbox state change, checkbox Updated value minus or add into Total accordingly
Following is the piece of jQuery Code
$('#Addcar').on('click', function() {
if($(this).html()=='Add') {
$(this).html('Remove');
var tot = parseFloat($('#TotalAmount').val()) + parseFloat($('#QuoteAmount').val());
var totcan = parseFloat($('#Cancelation').val()) + 2;
$('#TotalPrice').val(tot);
$('#Cancelation').val(totcan);
} else {
$(this).html('Add');
var tot = parseFloat($('#TotalPrice').val()) - parseFloat($('#QuoteAmount').val());
var totcan = parseFloat($('#Cancelation').val()) - 2;
$('#TotalPrice').val(tot);
$('#Cancelation').val(totcan);
}
});
$('#Cancelation').change(function(){
if($(this).is(':checked')){
total = parseFloat($('#TotalPrice').val()) + Number($(this).val());
} else {
total = parseFloat($('#TotalPrice').val()) - Number($(this).val());
}
$('#TotalPrice').val(total);
});
Here is the fiddle which explains better;
Updated Fiddle:
http://jsfiddle.net/55n8acus/7/
If QuoteAmount value added and checkbox value remove from Total and then remove QuoteAmount value , the result value will be wrong, it should be 52 not 48, the reason checkbox won't update and it still remove 4 from Total instead it should remove 2.
Thanks for all the help
Regards.
What I can understand from the question is that you want to subtract the value from total price, but you are accidentally using #TotalValue instead of #TotalPrice when you click on the checkbox, change the code to this, it will work as expected.
$('#Cancelation').change(function(){
if($(this).is(':checked')){
total = parseFloat($('#TotalPrice').val()) + Number($(this).val());
} else {
total = parseFloat($('#TotalPrice').val()) - Number($(this).val());
}
$('#TotalPrice').val(total);
});
here is the updated js fiddle :- jsfiddle.net/55n8acus/8
$('#Addcar').on('click', function() {
if($(this).html()=='Add') {
$(this).html('Remove');
var tot = parseFloat($('#TotalAmount').val()) + parseFloat($('#QuoteAmount').val());
var totcan = parseFloat($('#Cancelation').val()) + 2;
if(!$("#Cancelation").is(':checked')){
tot = tot -4;
}
$('#TotalPrice').val(tot);
$('#Cancelation').val(totcan);
$('#Cancel').html(totcan);
} else {
$(this).html('Add');
var tot = parseFloat($('#TotalPrice').val()) - parseFloat($('#QuoteAmount').val());
if(!$("#Cancelation").is(':checked')){
tot +=2;
}
var totcan = parseFloat($('#Cancelation').val()) - 2;
$('#TotalPrice').val(tot);
$('#Cancelation').val(totcan);
$('#Cancel').html(totcan);
}
});
$('#Cancelation').change(function(){
if($(this).is(':checked')){
total = parseFloat($('#TotalPrice').val()) + Number($(this).val());
} else {
total = parseFloat($('#TotalPrice').val()) - Number($(this).val());
}
$('#TotalPrice').val(total);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Add<br>
<input type="text" id="QuoteAmount" value="50" />
<input type="text" name="TotalAmount" id="TotalAmount" value="52" /><br>
<input type="text" name="TotalPrice" id="TotalPrice" value="0" /><br>
<input type="checkbox" id="Cancelation" value="2" checked> <span id="Cancel">2</span>

get the html of the child div if the checkbox in the parent div has been checked in javascript

I have the following HTML:
<div id="chkBox20">
<input type="checkbox" id="box20" name="rooms[]" value="20" class="box"/>
<div class="specialprice2" style="float:left;">68.00</div>
</div>
<div id="chkBox21">
<input type="checkbox" id="box21" name="rooms[]" value="21" class="box"/>
<div class="specialprice2" style="float:left;">68.00</div>
</div>
<div id="chkBox22">
<input type="checkbox" id="box22" name="rooms[]" value="22" class="box"/>
<div class="specialprice2" style="float:left;">155.00</div>
</div>
Some or none of those checkboxes might be checked.
If some of the boxes are checked, I have script that display the sum for checked checkboxes.
What I am trying now is to update the result if the user check or uncheck any of the checkboxes.
Here is the javascript that I have now:
$(document).ready(function(){
var sum = 0;
$('.specialprice').each(function(i, el) {
sum += parseInt($(el).html());
if(sum){
thesum = sum.toFixed(2);
}
});
sumPerRoom = (thesum * <?php echo $searchQueryNumOfDays;?>);
formatedSumPerRoom = sumPerRoom.toFixed(2);
$('.newprice').append(thesum +" € x Evenings: <?php echo $searchQueryNumOfDays ;?> = "+formatedSumPerRoom+" €");
});
// above part work just fine, problem is bellow.
//I guess that bellow I should try something with child div
//but i don't know how to do it
$(".box").click(function(){
var sum = 0;
$('.specialprice2').each(function(i, el) {
sum += parseInt($(el).html());
if(sum){
thesum = sum.toFixed(2);
}
});
alert(thesum);
});
Needles to say the sum alert the sum of all divs, and i want only the clicked ones.
If someone can help me to alert or to console log the updated price, I will find my way from there.
Regards, John
$('.box').on('change', function(){
calculate();
});
function calculate(){
var total = 0;
$('.box:checked').each( function(){
var price = parseFloat($(this).next('.specialprice2').text());
total = total + price;
});
alert(total.toFixed(2));
}
calculate();
JSFiddle
NEW: There is whole code that should work properly as far as php will.
var thesum = 0;
$(document).ready(function(){
var sum = 0;
$('.specialprice').each(function(i, el) {
sum += parseInt($(el).html());
if(sum){
thesum = sum.toFixed(2);
}
});
sumPerRoom = (thesum * <?php echo $searchQueryNumOfDays;?>);
formatedSumPerRoom = sumPerRoom.toFixed(2);
$('.newprice').append(thesum +" € x Evenings: <?php echo $searchQueryNumOfDays ;?> = "+formatedSumPerRoom+" €");
});
$(".box").click(function(){
var thesum = sum = 0; //UPDATE
$('.specialprice2').each(function(i, el) {
if($(this).parent().find(".box").is(":checked")){ //<---
sum += parseInt($(el).html());
if(sum){
thesum = sum.toFixed(2);
}
}
});
alert(thesum);
});
OLD: This code works perfectly:
$(".box").click(function(){
var thesum = sum = 0; //UPDATE
$('.specialprice2').each(function(i, el) {
if($(this).parent().find(".box").is(":checked")){ //<---
sum += parseInt($(el).html());
if(sum){
thesum = sum.toFixed(2);
}
}
});
alert(thesum);
});
What it does is getting parent of .specialprice2 element, then finds .box element in it and checks if checkbox is checked.

Categories

Resources