I am trying to make this work with the help of jQuery docs but not success so far.
I have two boxes paynow and payfull that has 0 initial value but I am filling these boxes dynamically (jQuery) with product prices.
Now I have to update these values further with select option to discount the price (multiply with data-percent). This is the HTML.
<select class="discount">
<option data-percent="0">Select Discount Coupon</option>
<option data-percent="5">ABCD</option>
<option data-percent="10">EFGH</option>
<option data-percent="15">IJKL</option>
</select>
<span class="price" id="paynow">$0.00</span>
<span class="price" id="payfull">$0.00</span>
EDIT: jQuery code
$(document).ready(function() {
// For Calculator
function Cost_Calculator() {
var Currency = '$';
var messageHTML = 'Please contact us for a price.';
function CostFilter(e) {
return e;
}
//Calculate function
function calculate() {
//Blank!
var CalSaveInfo = [];
$('#cost_calc_custom-data, #cost_calc_breakdown').html('');
//Calculate total
var calCost = 0;
var calculate_class = '.cost_calc_calculate';
$('.cost_calc_active').each(function() {
//Calculation
calCost = calCost + parseFloat($(this).data('value'));
//Add to list
var optionName = $(this).attr('value');
var appendName = '<span class="cost_calc_breakdown_item">' + optionName + '</span>';
var optionCost = $(this).attr('data-value');
var appendCost = '<span class="cost_calc_breakdown_price">' + Currency + optionCost + '</span>';
if (optionCost != "0") {
var appendItem = '<li>' + appendName + appendCost + '</li>';
}
//hidden data
var appendPush = ' d1 ' + optionName + ' d2 d3 ' + optionCost + ' d4 ';
$('#cost_calc_breakdown').append(appendItem);
CalSaveInfo.push(appendPush);
});
//Limit to 2 decimal places
calCost = calCost.toFixed(2);
//Hook on the cost
calCost = CostFilter(calCost);
var CustomData = '#cost_calc_custom-data';
$.each(CalSaveInfo, function(i, v) {
$(CustomData).append(v);
});
//Update price
if (isNaN(calCost)) {
$('#paynow').html(messageHTML);
$('#payfull').html(messageHTML);
$('.addons-box').hide();
} else {
$('#paynow').html(Currency + calCost);
$('#payfull').html(Currency + calCost);
$('.addons-box').show();
}
}
//Calculate on click
$('.cost_calc_calculate').click(function() {
if ($(this).hasClass('single')) {
//Add cost_calc_active class
var row = $(this).data('row');
//Add class to this only
$('.cost_calc_calculate').filter(function() {
return $(this).data('row') == row;
}).removeClass('cost_calc_active');
$(this).addClass('cost_calc_active');
} else {
// Remove class if clicked
if ($(this).hasClass('cost_calc_active')) {
$(this).removeClass('cost_calc_active');
} else {
$(this).addClass('cost_calc_active');
}
}
//Select item
var selectItem = $(this).data('select');
var currentItem = $('.cost_calc_calculate[data-id="' + selectItem + '"]');
var currentRow = currentItem.data('row');
if (selectItem !== undefined) {
if (!$('.cost_calc_calculate[data-row="' + currentRow + '"]').hasClass('cost_calc_active'))
currentItem.addClass('cost_calc_active');
}
//Bring in totals & information
$('#cost_calc_breakdown_container, #cost_calc_clear_calculation').fadeIn();
$('.cost_calc_hide').hide();
$('.cost_calc_calculate').each(function() {
calculate();
});
return true;
});
$('#cost_calc_clear_calculation').click(function() {
$('.cost_calc_active').removeClass('cost_calc_active');
calculate();
$('#cost_calc_breakdown').html('<p id="empty-breakdown">Nothing selected</p>');
return true;
});
}
//Run cost calculator
Cost_Calculator();
});
How about this one:
var totalPayNowPrice=parseFloat($('#paynow').text());
var totalPayFullPrice=parseFloat($('#payfull').text());
$('.discount').on('change',function(){
if(parseInt($('.discount option:selected').attr('data-percent'))){
$('#paynow').text((totalPayNowPrice*parseInt($('.discount option:selected').attr('data-percent')))+'$');
$('#payfull').text((totalPayFullPrice*parseInt($('.discount option:selected').attr('data-percent')))+'$');
}
});
Just put the $ sign in you spans after the numbers, in order to parse function would work.
JSFIDDLE
UPDATE
From another point I think there is a better solution to use prototype and store you current prices in spans inside global variable, then you can use them wherever you want. Here the pseudo prototype for your use, if you`d like just customize it for you using:
function Test(){
this.totalPayNowPrice=1;//the is 1 only for check code working
this.totalPayFullPrice=1;
}
Test.prototype={
init: function(){
var scope=this;
$('.discount').on('change',function(){
if(parseInt($('.discount option:selected').attr('data-percent'))){
$('#paynow').text((scope.totalPayNowPrice*parseInt($('.discount option:selected').attr('data-percent')))+'$');
$('#payfull').text((scope.totalPayFullPrice*parseInt($('.discount option:selected').attr('data-percent')))+'$');
}
},
updatePaynowPrice:function(newPrice){
this.totalPayNowPrice=totalPayNowPrice;
},
updatePayfullPrice:function(newPrice){
this.totalPayFullPrice=totalPayNowPrice;
}
}
you can use
$(document).ready(function(){
// get price from #paynow (just a number)
var getPaynow = $('#paynow').text().match(/\d+/);
// get price from #payfull (just a number)
var getPayfull = $('#payfull').text().match(/\d+/);
$('.discount').on('change', function(){
// get data-percent from selected option
var discount = parseFloat($(this).find('>option:selected').attr('data-percent'));
//alert(discount +'///'+ getPaynow+'///'+ getPayfull);
//update price for #paynow and #payfull
$('#paynow').text('$'+parseFloat(getPaynow - (getPaynow * discount / 100)));
$('#payfull').text('$'+parseFloat(getPayfull - (getPayfull * discount / 100)));
});
});
Working Demo
in your code you can update prices after this part of code
//Update price
if (isNaN(calCost)) {
$('#paynow').html(messageHTML);
$('#payfull').html(messageHTML);
$('.addons-box').hide();
} else {
$('#paynow').html(Currency + calCost);
$('#payfull').html(Currency + calCost);
$('.addons-box').show();
}
//get price from #paynow (just a number)
getPaynow = $('#paynow').text().match(/\d+/);
// get price from #payfull (just a number)
getPayfull = $('#payfull').text().match(/\d+/);
Related
I have 48 inputs, and for each input I need to get its value and add it to the total sum. Currently I am only getting the values of two inputs and adding them but how would it be better to make this a "foreach function"
$(document).ready(function() {
$('.margin .custom-input:nth-child(1)').change(function() {
updateTotal();
});
$('.margin .custom-input:nth-child(2)').change(function() {
updateTotal();
});
var updateTotal = function () {
var input1 = parseInt($('.margin .custom-input:nth-child(1)').val());
var input2 = parseInt($('.margin .custom-input:nth-child(2)').val());
var total = input1 + input2;
$(".marginAttachment").text("Durchschn. Attachmentniveau = " + total + "mm");
};
});
<div class="margin">
<input class="custom-input" type="text" value="0">
</div>
You have to use the jQuery each function. your final code will be like this
$(document).ready(function() {
$('.margin .custom-input').change(function() {
updateTotal();
});
var updateTotal = function () {
var total = 0;
$('.margin .custom-input').each(function() {
total += parseInt($(this).val());
});
$(".marginAttachment").text("Durchschn. Attachmentniveau = " + total + "mm");
};
});
Or, you just directly get the value of active input so that no need to implement for loop. like this
$(document).ready(function() {
var total = 0
$('.margin .custom-input').change(function() {
total += $(this).val()
$(".marginAttachment").text("Durchschn. Attachmentniveau = " + total + "mm");
});
});
jQuery does have foreach support, in form of the .each() function:
var sum = 0;
$('.margin .custom-input').each(function() {
sum += parseInt($(this).val());
});
The country is changing along side the shipping. I could alert my shipping but will refuse to display in my div. What could be wrong? All calculations working well and displays well except for the #usashipping please help. My country changes and give the correct value for the calculation. The shipping fee just will not display.
<!-- language: lang-js -->
<script type="application/javascript">
var price= "";
var userprice="";
var flpay='';
var total='';
var shipping='';
var fees=30.0;
$('#country').change(function() {
var input = $(this).val();
var shipping;
if (input == 40) {
shipping = 10.0;
$('#usashipping').html('10.0');
} else if (input == 236) {
shipping = 10.0;
$('#usashipping').html('10.0');
} else {
shipping = 30.0;
$('#usashipping').html('30.0');
}
if(fees=='') {
$('#fees').html(30);
}
if(flpay=='')
{
$('#flpay').html(2*19.99);
}
if(total=='')
{
var tot=19.99*2.0 +30.0 + shipping;
var total= tot.toFixed(2);
$('#total').html(total);
}
$('.add').click(function() {
var $input = $(this).next();
var currentValue = parseInt($input.val());
var newinput= currentValue + 1;
$('#gems').val(newinput);
(newinput);
if(newinput==1)
{
var np1=(19.99*2.0);
flpay= np1.toFixed(2);
$('#flpay').html(flpay);
var tot= (fees + shipping + flpay);
var total= tot.toFixed(2);
$('#total').html(total);
var newp=19.99;
var price= newp.toFixed(2);
$('#price').html(price);
useprice= 19.99;
}
else if(newinput>1)
{
//useprice=useprice;
var newprice= 19.99 + (9.99*(newinput-1));
var np1 =(2*newprice);
var flpay = np1.toFixed(2);
$('#flpay').html(flpay);
var tot =( fees + shipping + (2*newprice) );
var total= tot.toFixed(2);
$('#usashipping').html(shipping);
$('#total').html(total);
var newp= newprice.toFixed(2);
$('#price').html(newp);
}
// newprice= price * 2;
// $('#price').html(newprice);
});
<!-- language: lang-html -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div>
First & Last Months Payment = $<span data-first-last-month-fees="" id="flpay"></span>
</div>
<div>
Shipping Fee = $<span data-shipping-fee="" id="usashipping"></span>
</div>
<div>
Total due today : $<span data-total-due="" id="total"></span>
</div>
Your code should work perfectly, but there are few things that you could improve in your code:
Instead of declaring shipping variable 3 times in each condition, you need to declare it only once, then update it in each condition, and make sure it's stored as a string so it can be displayed correctly in your HTML.
Instead of updating the HTML content of your span in every condition, just update it with the shipping amount in the end.
This is how should be your code:
$('#country').change(function() {
var input = $(this).val();
var shipping;
if (input == 40) {
shipping = '10.0';
} else if (input == 236) {
shipping = '20.0';
} else {
shipping = '30.0';
}
$('#usashipping').html(shipping);
});
Demo:
$('#country').change(function() {
var input = $(this).val();
var shipping;
if (input == 40) {
shipping = '10.0';
} else if (input == 236) {
shipping = '20.0';
} else {
shipping = '30.0';
}
$('#usashipping').html(shipping);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<select id="country">
<option value="40">40</option>
<option value="236">236</option>
<option value="100">100</option>
</select>
<div>
Shipping Fee = $<span data-shipping-fee="" id="usashipping"></span>
</div>
I can see error showing in your code. I found "$('.add').click" inside "$('#country').change". Also "$('#country').change" function you declared local variable "var shipping;" that's why no change on global "shipping;" value but you using it inside "$('#country').change" function. I modified little bit now try with following code and comment reply if not work for you:
var price= "";
var userprice="";
var flpay='';
var total='';
var shipping='';
var fees=30.0;
$('#country').change(function() {
var input = $(this).val();
if (input == 40) {
shipping = 10.0;
$('#usashipping').html('10.0');
} else if (input == 236) {
shipping = 10.0;
$('#usashipping').html('10.0');
} else {
shipping = 30.0;
$('#usashipping').html('30.0');
}
if(fees=='') {
$('#fees').html(30);
}
if(flpay=='')
{
$('#flpay').html(2*19.99);
}
if(total=='')
{
var tot=19.99*2.0 +30.0 + shipping;
var total= tot.toFixed(2);
$('#total').html(total);
}
})
$('.add').click(function () {
var $input = $(this).next();
var currentValue = parseInt($input.val());
var newinput = currentValue + 1;
$('#gems').val(newinput);
(newinput);
if (newinput == 1) {
var np1 = (19.99 * 2.0);
flpay = np1.toFixed(2);
$('#flpay').html(flpay);
var tot = (fees + shipping + flpay);
var total = tot.toFixed(2);
$('#total').html(total);
var newp = 19.99;
var price = newp.toFixed(2);
$('#price').html(price);
useprice = 19.99;
}
else if (newinput > 1) {
//useprice=useprice;
var newprice = 19.99 + (9.99 * (newinput - 1));
var np1 = (2 * newprice);
var flpay = np1.toFixed(2);
$('#flpay').html(flpay);
var tot = (fees + shipping + (2 * newprice));
var total = tot.toFixed(2);
$('#usashipping').html(shipping);
$('#total').html(total);
var newp = newprice.toFixed(2);
$('#price').html(newp);
}
// newprice= price * 2;
// $('#price').html(newprice);
})
I only changed the div id from #usashipping to something else and it works just fine. Maybe #usashippingis now a constant in jquery library.
When I click on selected option product price update shows wrong.
Here is my code
<div class="container">
<div class="row">
<div class="col-md-6">Initial Price: <span id="thisIsOriginal" class="">$45,000.00</span></div>
<div class="col-md-6">Total: <span id="total">$45,000.00</span></div>
</div>
<div class="row">
<select class="optionPrice" name="select-1">
<option value="">Please Select</option>
<option data-price="2,000.00" value="20">+$2,000.00</option>
</select>
</div>
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('.optionPrice').change(function () {
var OriginalPrice = $('#thisIsOriginal').text();
var OriginalCurrency = OriginalPrice.substring(0, 1);
OriginalPrice = OriginalPrice.substring(1);
var total = 0;
$('.optionPrice').each(function () {
if ($(this).find('option:selected').attr('data-price') != 0 && $(this).find('option:selected').attr('data-price') != undefined) {
console.log($('option:selected', this).attr("data-price"));
total += parseFloat($('option:selected', this).attr('data-price'));
}
});
var newTotal = parseFloat(OriginalPrice) + parseFloat(total);
$('#total').text('$' + newTotal.toFixed(2));
});
});
</script>
How to solve this issue.I want after select the price shows 47,000.
The problem with your code is,
Your price contains , inside it. So after parseFloat() the values after the comma is getting truncated. You need to remove the commas before using parseFloat.
Changes need on the following lines,
total += parseFloat($('option:selected', this).attr('data-price').replace(/,/g, ""));
and
var newTotal = parseFloat(OriginalPrice.replace(/,/g, "")) + parseFloat(total);
Updated Fiddle
$('.optionPrice').change(function() {
var OriginalPrice = $('#thisIsOriginal').text();
var OriginalCurrency = OriginalPrice.substring(0, 1);
OriginalPrice = OriginalPrice.substring(1);
var total = 0;
$('.optionPrice').each(function() {
if ($(this).find('option:selected').attr('data-price') != 0 && $(this).find('option:selected').attr('data-price') != undefined) {
console.log($('option:selected', this).attr("data-price"));
total += parseFloat($('option:selected', this).attr('data-price').replace(/,/g, ""));
}
});
var newTotal = parseFloat(OriginalPrice.replace(/,/g, "")) + parseFloat(total);
$('#total').text('$' + newTotal.toFixed(2));
});
Edit for Getting comma separated value,
$('.optionPrice').change(function() {
var OriginalPrice = $('#thisIsOriginal').text();
var OriginalCurrency = OriginalPrice.substring(0, 1);
OriginalPrice = OriginalPrice.substring(1);
var total = 0;
$('.optionPrice').each(function() {
if ($(this).find('option:selected').attr('data-price') != 0 && $(this).find('option:selected').attr('data-price') != undefined) {
console.log($('option:selected', this).attr("data-price"));
total += parseFloat($('option:selected', this).attr('data-price').replace(/,/g, ""));
}
});
var newTotal = parseFloat(OriginalPrice.replace(/,/g, "")) + parseFloat(total);
newTotal = numberWithCommas(newTotal);
$('#total').text('$' + newTotal + ".00");
});
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
Below code appends text in a box how to avoid entering duplicate values..?
$('#plan td.n').click(function(){
$(this).html('B').css("background-color","red");
$("input:text").val(this.id);
var toAdd = $("input[name=checkListItem]").val();
$(".list").append("<div class = 'item'>" + toAdd + "</div>")//add the seat number to box
});
I'd probably do something like this below. Hope it helps
var lookupObj = {};
var toAdd = $("input[name=checkListItem]").val();
if(!lookupObj[toAdd]) {
$(".list").append("<div class = 'item'>" + toAdd + "</div>")
lookupObj[toAdd] = true;
}
Assuming your markup looks like this:
<input name="checkListItem" value=""/>
<input type="submit" class="addItem" value="Add/Remove"/>
<div class="list">
</div>
You can add an event which filters items which match the text (exactly) of the current .val() of the checkListItem input, which lets you delete the item in the list if it is a duplicate.
$('.addItem').on('click', function() {
var toAdd = $("input[name=checkListItem]").val(),
exists = $('.item').filter(function() {
return $(this).text() == toAdd;
});
if (exists.length > 0) {
exists.remove();
} else {
$(".list").append("<div class = 'item'>" + toAdd + "</div>");
}
});
https://jsfiddle.net/milesrobinson/563h1fq6/
// if you don't care the performance, this is the easy way
var finded = false;
$(".list > .item").each(function(idx){
if (toAdd === $(this).html()) {
finded = true;
return false;
}
});
if (!finded) {
$(".list").append("<div class = 'item'>" + toAdd + "</div>")
}
I running a similar script to this script from fiddle
http://jsfiddle.net/QmTNZ/2/
I tried to modify it to work with my table.
Here is the link to the table on the product page
http://styleso1.nextmp.net/dev/shop/safari-pu-sleeve-jacket.html
I need it to calculate the Qty ( input box, Column 4) X the unit price ( Column 5 ) and show the sum in column 6
How would i modify the JS to do this?
Here is what i have for the JS
$(function(){
function ca(){
var $overall = 0;
$("tr.sum").each(function() {
var $qnt = $(this).find(".qty");
var $price = $(this).find("td").eq(1);
console.log($qnt + " | " + $price);
var sum = parseFloat($price.text()) * parseFloat($qnt.val());
$(this).find(".a-center1").text(sum);
$overall += sum;
});
$("#total").text($overall);
}
$(function() {
ca();
$('input.qty').bind('change keyup',function(){ca();});
});
Any Help would be very appreciated
Try this
$("tr.sum").each(function() {
var $qnt = $(this).find(".qty");
var $price = $(this).find("td:eq(4)").find('.price');
console.log($qnt + " | " + $price);
var pri = $price.text();
pri = pri.replace('$', '');
var sum = parseFloat(pri) * parseFloat($qnt.val());
$(this).find("td").eq(5).text('$' + sum);
$overall += sum;
});
$("#total").text('$' +$overall);
Check Fiddle
You can save some DOM searching and text parsing by doing some simple things like adding the unit price as a data attribute to the row and retrieving it with jQuery data() method
HTML
<tr class="sum" data-unit_price="10.00">
JS
function ca(){
var $overall = 0;
$("tr.sum").each(function() {
var $row=$(this);
var $qnt = $(this).find(".qty");
var cost = $row.data('unit_price');
var sum = cost * parseFloat($qnt.val());
$(this).find("td").eq(5).text('$' +sum);
$overall += sum;
});
$("#total").text('$' +$overall);
}
$(function() {
ca();
$('input.qty').bind('change keyup', ca);
});
DEMO: http://jsfiddle.net/Jk976/3/