Change prices based on checkbox click - javascript

im currently looking for help in this matter.
The problem here is that instead of doing the checkbox value + the previous value it is adding it all together like placing "10" and after other checkbox click it adds the value to it and does not count it like "1020" instead of doing 10+20
$(document).ready(function() {
$("input[type=checkbox]").click(function() {
var total = 0;
$("input[type=checkbox]:checked").each(
function() {
total = total + parseInt($(this).val());
});
var input = document.getElementById("valor");
input.value += input.value + total;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Comissões Técnicas</label>
<label class="container newlabel">CPT
<input type="checkbox" value="10" name="cpt" >
<span class="checkmark"></span>
</label><br>
<label class="container newlabel">CPGA (Gratuito para Sócios da SPG)
<input type="checkbox" value="10" name="cpga" >
<span class="checkmark"></span>
</label><br>
<input id="valor" type="text">

Check if repeatedly click on checkbox should be handled also on uncheck score should reduced.
$(document).ready(function() {
$("input[type=checkbox]").click(function() {
var total = 0;
total = parseInt(document.getElementById("valor").value);
if(isNaN(total)){
total = 0;
}
if($(this).prop('checked')){
total = total + parseInt($(this).val());
} else {
total = total - parseInt($(this).val());
};
var input = document.getElementById("valor");
input.value = total;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Comissões Técnicas</label>
<label class="container newlabel">CPT
<input type="checkbox" value="10" name="cpt" >
<span class="checkmark"></span>
</label><br>
<label class="container newlabel">CPGA (Gratuito para Sócios da SPG)
<input type="checkbox" value="20" name="cpga" >
<span class="checkmark"></span>
</label><br>
<input id="valor" type="text">

The code
input.value += input.value + total;
means (since input.value is a String), concatenate input.value with total after making sure total is a String. Don't use the += and be sure to use parseInt() on anything that you want to be a number.
$(document).ready(function() {
$("input[type=checkbox]").click(function() {
var total = 0;
$("input[type=checkbox]:checked").each(
function() {
total = total + parseInt($(this).val());
});
var input = document.getElementById("valor");
/*
* You don't need +=
* You do need to parseInt
* You need to make sure to handle empty String ""
*/
input.value = (parseInt(input.value, 10) || 0) + total;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Comissões Técnicas</label>
<label class="container newlabel">CPT
<input type="checkbox" value="10" name="cpt" >
<span class="checkmark"></span>
</label>
<br>
<label class="container newlabel">CPGA (Gratuito para Sócios da SPG)
<input type="checkbox" value="10" name="cpga" >
<span class="checkmark"></span>
</label><br>
<input id="valor" type="text">

Please correct me, if I don't quite understand your problem, but shouldn't you just have to change input.value += input.value + total; to input.value = total; for the required result?

As you are using jQuery and I love to user reduce method I can advice you this solution
$(document).ready(function() {
$("input[type=checkbox]").click(function() {
var total = $('input[type=checkbox]:checked').toArray().reduce(function(pre, post) {
return pre + parseInt($(post).val());
}, 0);
$('#valor').val(total);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Comissões Técnicas</label>
<label class="container newlabel">CPT
<input type="checkbox" value="10" name="cpt" >
<span class="checkmark"></span>
</label><br>
<label class="container newlabel">CPGA (Gratuito para Sócios da SPG)
<input type="checkbox" value="20" name="cpga" >
<span class="checkmark"></span>
</label><br>
<input id="valor" type="text">
If your value is always a number you can use value / 1 to convert number string into numeric type. This only if you are SURE that the number will be always a number and not a string containing number, eg. 11.jpg is not valid.
This is a performance test for your case:
https://jsperf.com/parseint-versus-divide-by-one/1
So you can rewrite the code as:
$(document).ready(function() {
$("input[type=checkbox]").click(function() {
var total =
$('input[type=checkbox]:checked').toArray().reduce(function(pre, post) {
var val = $(post).val() / 1;
return pre + (val ? val : 0);
}, 0);
$('#valor').val(total);
});
});

Related

Jquery checkbox calculator keeps returning NaN

i heve calucalot problem with jquery.
Custom Wpform Checkbox Field returning NaN.
HTML
<div class="wpforms-payment-total">
$ 85
</div>
<input type="checkbox" name="myBox2" size="12" />
With Two Coat + 15%
<b><span id="totalfinal"></span> </b>
JS
jQuery(document).ready(function() {
var Valuee = $('.wpforms-payment-total');
jQuery('input[name="myBox2"]').on('click', function() {
if (jQuery(this).is(':checked')) {
var finalprice = parseInt($('.wpforms-payment-total').text()) * 1.15;
jQuery('#totalfinal').text(finalprice.toFixed(2));
} else {
var finalprice = parseInt($('.wpforms-payment-total').text());
jQuery('#totalfinal').text(finalprice.toFixed(2));
}
});
});
You can not parse any String to a number, you can either split your total amount in a prefix and a number oder you have to remove anything but the number from the string.
As I think storing the number in its own Tag makes more sense, here is a working snipet that does that.
jQuery(document).ready(function() {
const Valuee = $('.wpforms-payment-total');
jQuery('input[name="myBox2"]').on('click', function() {
let finalprice = parseInt(Valuee.text().replace(/^[^0-9,.]+/, "").match( /^[0-9,.]+/g, '')[0]);
if (jQuery(this).is(':checked')) {
finalprice *= 1.15;
}
jQuery('#totalfinal').text(finalprice.toFixed(2));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wpforms-payment-total">
$ 85
</div>
<input type="checkbox" name="myBox2" id="myBox2" size="12" />
<label for="myBox2">With Two Coat + 15%</label>
<br>
<b><span id="totalfinal"></span></b>
Here is another methode, using data attributes to make it more versityle, maybe that is something you might want to learn about when dealing with jQuery:
jQuery(document).ready(function() {
function updateTotalFinal(){
const subtotalValue = +jQuery('.wpforms-payment-total').text().replace(/^[^0-9,.]+/, "").match( /^[0-9,.]+/g, '')[0];
let totalValue = subtotalValue;
const totalFinalElem = jQuery("#totalfinal");
jQuery("input.change-total:checked").each(function() {
const $this = jQuery(this);
if ($this.is("[data-method=add]")) {
totalValue += +$this.data("amount");
} else if ($this.is("[data-method=multiply]")) {
totalValue += subtotalValue * $this.data("amount");
}
});
totalFinalElem.text(`$ ${totalValue}`);
}
jQuery("input.change-total").on("change", function() {
updateTotalFinal();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wpforms-payment-total">
85€
</div>
<label>
<input type="checkbox" class="change-total" name="myBox2" size="12" data-amount="0.15" data-method="multiply" />
With Two Coat + 15%
</label>
<br>
<label>
<input type="checkbox" class="change-total" name="myBox3" size="12" data-amount="5" data-method="add" />
With extra Pants + $ 5
</label>
<br>
<b><span id="totalfinal">$ 85</span></b>
You must first remove all non-digits character from price then use that,
Notice that for checkbox it is better to use change event
jQuery('input[name="myBox2"]').on('change', function() {
// Remove any non-digits character
var price = parseInt($('.wpforms-payment-total').text().replace( /^\D+/g, ''));
if (jQuery(this).is(':checked')) {
var finalprice = price * 1.15;
jQuery('#totalfinal').text(finalprice.toFixed(2));
} else {
jQuery('#totalfinal').text(price.toFixed(2));
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wpforms-payment-total">
$ 85
</div>
<input type="checkbox" name="myBox2" size="12" />
With Two Coat + 15%
<b><span id="totalfinal"></span> </b>

Get the values of column if checkbox/radio box is checked

I was wondering how to get the values in a certain column if the checkbox or radio button on that particular row is checked. I've already started and came up with this:
<script>
var Step = <?php echo $_SESSION['Step'] ?>;
if(Step == 3 || Step == 4 ) { setInterval(ScriptUpdate, 1000); }
function ScriptUpdate()
{
if(Step == 3)
{
var checked = $("input:checkbox:checked").length;
var radioButtonSelectedCount = $(document.querySelectorAll('input[type=radio]:checked')).parent().filter(function() {return $(this).text().trim()=="Yes"}).length;
var Counter = checked + radioButtonSelectedCount;
$('#ES3I').text(Counter + ' Items');
var price = 0;
$("#TextBookTB tr:gt(0) td:nth-child(6)").each(function(td){
var content = $(this).text();
if($.isNumeric(content)) {
price = price + Number(content);
console.log(price);
}
});
$("#ES3P").text(price);
}
}
</script>
The goal is that: when user checks the check box or answered 'yes' in the radio button it is the only time it will count the value. Apologies, I am really bad at jquery/javascript.
EDIT: html code as requested. The current output of the timer takes all of the values in all rows of that particular column.
<label class="radio-inline">
<input form="ES3S" type="radio" name="Textbook'.$i.'" value="'.$Result[$i]['ID'].'"> Yes
</label>
<label class="radio-inline">
<input form="ES3S" type="radio" name="Textbook'.$i.'" value="-1">No
</label>
<span class="d-inline-block" data-toggle="popover" title="Error" data-content="This book is required by the school. If you want to cancel this out, proceed to the principals office with the book for review." data-trigger="hover">
<input form="ES3S" required checked onclick="return false;" type="checkbox" value="'.$Result[$i]['ID'].'" name="Textbook'.$i.'">
</span>
try this if you are using table
var count = 0;
$('#TABLEID').find('tr').each(function () {
var tableRow = $(this);
if (tableRow.find('input[type="checkbox"]').is(':checked')) {
count += 1;
}
});
when user checks the check box or answered 'yes' in the radio button it is the only time it will count the value
$(function() {
var selector = 'input[name^="Textbook"]';
$(selector).on('click', function() {
var checked = $(selector + ':checked').map(function() {
return {
'type': this.type,
'value': this.value
};
}).get().filter(function(o) {
return '-1' !== o.value; // skip if value = -1(No)
});
console.log('checked inputs', checked);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<label><input type="radio" name="Textbook1" value="1"/>Yes</label>
<label><input type="radio" name="Textbook1" value="-1"/>No</label>
<input type="checkbox" name="Textbook1" value="1" />
</div>
<div>
<label><input type="radio" name="Textbook2" value="2"/>Yes</label>
<label><input type="radio" name="Textbook2" value="-1"/>No</label>
<input type="checkbox" name="Textbook2" value="2" />
</div>

increase and decrease value using a radio button

I am developing an eCommerce system.
Let say if user has total of 1200 right.
If he chooses fast delivery options
40 should be added to total that means at the end amount should be changed from 1200 to 1240.
I have a developed a kind of application for that.
I don't know what but the value is not increment. Don't know what but I need a solution,
Here is my code:
<label><input type="radio" name="optradio" id="target">
<span class="label label-success">Fast Delivery</span></label>
<div id="output">10</div>
<div id="savevalue" style="visibility:hidden"></div>
<label><input type="radio" name="optradio" id="target2">
<span class="label label-success">Regular Delivery</span></label>
My Javascript code:
$('#target').click(function() {
var savevalue = $('#savevalue').text();
var output = $('#output').text();
if (savevalue==null || savevalue=="")
{
output = output*1 + 40;
savevalue = output;
$('#output').html(function(i, val) { return output});
$('#savevalue').html(function(i, val) { return savevalue});
}
});
$('#target2').click(function() {
var savevalue = $('#savevalue').text();
var output = $('#output').text();
if (output==savevalue)
{
output = output*1 - 40;
$('#output').html(function(i, val) { return output });
}
});
Try this :
HTML :
<p id="price">100</p>
<input type="radio" name="delivery" id="delivery1" value="normal" checked> Normal <br>
<input type="radio" name="delivery" id="delivery2" value="fast"> Fast
Js:
$(document).ready(function(){
$('#delivery1,#delivery2').change(function(){
price = $('#price').text();
if($('#delivery2').is(':checked')) {
price = parseInt(price) + 40;
} else {
price = parseInt(price) - 40;
}
$('#price').text(price);
});
});
can you check on my fiddle https://jsfiddle.net/3422ntLh/.
In my solution, check the html code.
<label>
<input type="radio" name="delivery" id="target" speed="fast">
<span class="label label-success">Fast Delivery</span></label>
<div id="output">10</div>
<div id="original" value="10" style="visibility:hidden"></div>
<label>
<input type="radio" name="delivery" id="target2" speed="normal">
<span class="label label-success">Regular Delivery</span></label>
I saved the value of the good in $('#original).
This is my JS code:
$('input:radio[name="delivery"]').change(function() {
alert($('#original').attr('value'));
$('#output').html($('#original_cost').attr('value'));
if ($(this).attr('speed') == 'fast') {
var extra_shipping_fee = 40;
var current_price = parseInt($('#original').attr('value'));
var new_price = current_price + extra_shipping_fee;
$('#output').html(new_price);
} else {
$('#output').html($('#original').attr('value'));
}
})
The code is not refine, but it will give you some insights on how to continue

How to calculate the total value of each section separately: Jquery

I have more than 10 section that included three inputs in each section as follows:
<div class="product_quantity">
<div class="color-quantity">
<input onkeydown="return myFunction(event);" name="custom_small" class="custom_small" type="text">
<input onkeydown="return myFunction(event);" name="custom_medium" class="custom_medium" type="text">
<input onkeydown="return myFunction(event);" name="custom_large" class="custom_large" type="text">
</div>
<div class="color-quantity">
<input onkeydown="return myFunction(event);" name="white_small" class="custom_small" type="text">
<input onkeydown="return myFunction(event);" name="white_medium" class="custom_medium" type="text">
<input onkeydown="return myFunction(event);" name="white_large" class="custom_large" type="text">
</div>
</div>
I am calculating the product quantity from each section but its giving me the whole amount of products on the basis of amount entered in every input. but i want the amount of products in section separately
I am using jQuery to do so please check the code and recommend the changes as required:
jQuery(".color-quantity input").each(function () {
if (this.value) {
quantity += (this.value) * 1;
classname = jQuery(this).attr('class');
arr.push(classname);
}
if (quantity == '') {
quantity = 0;
}
});
You can get total off each section as an array like following.
var arr = $('.color-quantity').map(function () {
var total = 0;
$('input', this).each(function () {
total += this.value * 1;
});
//do some stuff
if (total < 50) {
$('.btn-cart').removeAttr("onclick");
}
return total;
}).get();
console.log(arr)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="color-quantity">
<input type="text" value="1">
<input type="text" value="2">
<input type="text" value="3">
</div>
<div class="color-quantity">
<input type="text" value="4">
<input type="text" value="5">
<input type="text" value="6">
</div>
You might try a nested loop. first loop through the color-quantity divs, then through the inputs. like this:
jQuery(".color-quantity").each(function () {
var quantity = 0;
$(this).find('input').each(function() {
if (this.value) {
quantity += (this.value) * 1;
classname = jQuery(this).attr('class');
arr.push(classname);
}
if (quantity == '') {
quantity = 0;
}
});
// here is where you can get the total value for each div
});

Javascript multiple update the same field

FIDDLE: http://jsfiddle.net/hReB3/6/
Javascript code:
$('#qty').keyup(function(){
if($(this).val() != '' && isNumber($(this).val()) && $(this).val() > 0)
{
var price = $('#real_price').val() * 1;
var qty = $(this).val() * 1;
var total = price * qty;
$('#price').html(total);
}
else
{
$('#price').html('500');
}
});
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
If I'm updating the price for the first field, it works fine, but for the second doesnt.
I'm new into javascript :).
JSFiddle
Using classes on your fields instead of IDs (IDs must be unique) and enclosing them within a parent DIV would allow you to use this code and gives you scope to add as many sections to your page as you need.
HTML
<div>
Price $<span class="price">500</span>
<input type="hidden" class="real_price" value="500" />
<input type="text" class="qty" value="1" />
</div>
<div>
Price $<span class="price">500</span>
<input type="hidden" class="real_price" value="500" />
<input type="text" class="qty" value="1" />
</div>
JS
$('.qty').keyup(function () {
var $me = $(this),
$parent = $me.parent('div'),
total = 500;
if (isNumber($me.val()) && $me.val() > 0)
{
var price = $parent.find('.real_price').val() * 1,
qty = $me.val() * 1;
total = price * qty;
}
$parent.find('.price').html(total);
});
You could also replace your hidden fields with data-price attributes as shown here JSFiddle
Can you try this, You can't able to use id value in more elements, instead that you can use classname etc, I have updated your fiddle code,
HTML:
Price $<span id="price_qty_1">500</span>
<input type="hidden" id="real_price_qty_1" value="500" />
<input type="text" id="qty_1" class="qty" value="1"/><br />
Price $<span id="price_qty_2">500</span>
<input type="hidden" id="real_price_qty_2" value="500" />
<input type="text" id="qty_2" class="qty" value="1"/>
Jquery:
$('.qty').keyup(function(){
if($(this).val() != '' && isNumber($(this).val()) && $(this).val() > 0)
{
var idAt = $(this).attr('id');
var price = $('#real_price_'+idAt).val() * 1;
var qty = $(this).val() * 1;
var total = price * qty;
$('#price_'+idAt).html(total);
}
else
{
$('#price_'+idAt).html('500');
}
});
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
Demo : http://jsfiddle.net/hReB3/10/
Try this
<input type="text" id="qty1" value="1"/><br />
<input type="text" id="qty2" value="1"/>
$('#qty1,#qty2').keyup(function(){})
And in the price evaluation time replace this with
$('#price').html(total);
with
($(this).attr('id')=="qty1") ? $('#price1').html(total) : $('#price2').html(total);

Categories