Jquery checkbox calculator keeps returning NaN - javascript

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>

Related

Jquery Hide Div element if length greater then

I Want to hide element if another div's length is greater than 0, otherwise show the div
i have this code but it is not working for me :(
<div id="myid">90.00</div>
<div class="myclass">99.00</div>
JS code
$(document).ready(function() {
if($('#myid').length > 2){
$('.myclass').hide();
}
});
First edit your question by your new detail;
Then set your condition inside your updateTotalFinal function
jQuery(document).ready(function() {
function updateTotalFinal(){
const subtotalValue = +jQuery('.wpforms-payment-total').text().replace(/^[^0-9,.]+/, "").match( /^[0-9,.]+/g, '');
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 = totalValue * $this.data("amount");
} else if ($this.is("[data-method=multiply]")) {
totalValue += subtotalValue * $this.data("amount");
}
});
totalFinalElem.text(`${totalValue.toFixed(2)}`);
// IF YOU WANT CHECK THAT ANY VALUE FOR totalfinal IS EXIST USE THIS
if($('#totalfinal').text().length ){
$('.wpforms-payment-total').hide();
}
// IF YOU WANT CHECK THAT totalfinal IS GREATHER THAN ZERO USE THIS
/* if(parseInt( $('#totalfinal').text()) > 0 ){
$('.wpforms-payment-total').hide();
} */
}
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">
97
</div>
<tr>
<td>
<input type="checkbox" class="change-total" name="myBox2" size="12" data-amount="0.15" data-method="multiply" value="100" />
With Two Coat + 15%
</td>
<td>
<input type="checkbox" class="change-total" name="myBox3" size="12" id="myCheck" data-amount="0.9" data-method="add" />
With My Own Paint
</td>
</tr>
<br>
<b><span id="totalfinal"></span></b>
i have this code and want to hide
class "wpforms-payment-total" when "totalfinal" is calculated
<div class="wpforms-payment-total">
97
</div>
<tr>
<td>
<input type="checkbox" class="change-total" name="myBox2" size="12" data-amount="0.15" data-method="multiply" value="100" />
With Two Coat + 15%
</td>
<td>
<input type="checkbox" class="change-total" name="myBox3" size="12" id="myCheck" data-amount="0.9" data-method="add" />
With My Own Paint
</td>
</tr>
<br>
<b><span id="totalfinal"></span></b>
JS
jQuery(document).ready(function() {
function updateTotalFinal(){
const subtotalValue = +jQuery('.wpforms-payment-total').text().replace(/^[^0-9,.]+/, "").match( /^[0-9,.]+/g, '');
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 = 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();
});
});
$(document).ready(function() {
if($('#totalfinal').text() > 0){
$('.myclass').hide();
}
});

Change prices based on checkbox click

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);
});
});

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

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);

Get value from element id instead of name in javascript

I have some line of javascript which is works well if it gets value from the same series of names. But I have a problem later when each values passed to another page which I'd like to break down which value is belongs to. So the question is how can I change the way the script calculate the value from 'name' to 'id'. As the codes below:
<script type="text/javascript">
//auto commas
function doThousands(n) {
n = '' + n;
if (n.length < 4) return n;
var c = n.length % 3;
var pre = n.substring(0, c);
return pre + (pre.length? ',' : '') + n.substring(c).match(/\d{3}/g).join(',');
}
//sub total
function checkTotal() {
document.cc_form.total.value = '';
var sum = <?=$days*$_rate*$_rooms?>;
for (i=0;i<document.cc_form.cost.length;i++) {
if (document.cc_form.cost[i].checked) {
sum = sum + parseInt(document.cc_form.cost[i].value);
}
}document.cc_form.total.value = doThousands(sum);
}
</script>
And this is the HTML:
<form name="cc_form" id="cc_form" method="post" action="/">
<label for="transfer1"><input type="checkbox" id="transfer1" name="cost" value="800" autocomplete="off" onchange="checkTotal()" /> Taxi (800 THB | 2 pax)</label><br />
<label for="transfer2"><input type="checkbox" id="transfer2" name="cost" value="1200" autocomplete="off" onchange="checkTotal()" /> Mini Van (1,200 THB | 6 pax)</label><br />
<label for="xbed"><input type="checkbox" id="xbed" name="cost" value="1200" autocomplete="off" onchange="checkTotal()" /> Extra Bed (1,200 THB)</label><br />
<input type="text" id="total" name="total" />
</form>
document.getElementById http://www.w3schools.com/jsref/met_doc_getelementbyid.asp

Categories