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')
}});
Related
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 +" €");
};
};
});
};
I would like to add an exception or condition in this code.
var a = 0;
$(document).ready(function() {
$(document).on("change", "#txtInput" ,function(){
$("#contenido").append("<tr><td>"+$("#txtInput").val()+"</td></tr>");
a += 1;
var str = 'Total Bianuales: '
$('p').html(str + a);
}
)
});
This is how it works: I get a value with the ID txtInput. I got some condition about this ID up in my code but I want to apply it when it add the value in a table that it's created. How do I make a condition that only append the value I get from txtInput when it's major or equal than 9?
Thanks for your help anyway!
Remember that change fires when input looses focus so you will need to click out of the control to cause it to fire. If you wanted it to fire on each keystroke then you want the input event.
var a = 0;
$(document).on("change", "#txtInput",function(){
var inputLength = this.value.length;
if (inputLength <= 8) { return; }
$("#contenido").append("<tr><td>" + this.value + "</td></tr>");
$("p").html('Total Bianuales: ' + (++a));
});
<input id="txtInput" />
<table id="contenido"></table>
<p></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
var a = 0;
$(document).ready(function() {
$(document).on("change", "#txtInput" ,function(){
var textinput = parseInt($(this).val());
if (textinput > 8) {
$("#contenido").append("<tr><td>"+$(this).val()+"</td></tr>");
a += 1;
var str = 'Total Bianuales: '
$('p').html(str + a);
}}
);
});
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/
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>
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.