Update price on change inlcuding on select - javascript

This is my fiddle:
https://jsfiddle.net/btekbtek/6gxztk4f/6/
When I type qty, I automatically calculate price.
I want also include select option that is adding
£1 per 1 qty.
If someone type 10 qty - price should be qty10*(£1*10)*price
Currently when I add:
// update price if option change
var optionprice = 0;
var getPriceOption = function() {
jQuery("#select_21").change(function() {
if (jQuery(this).val() === '63') {
optionprice = 0;
} else {
optionprice = 1;
}
}); //end update optionprice
return optionprice;
}; //end get PriceOption
console.log(getPriceOption);
getPriceOption is undefined. I was trying to add it after before and same result.
I cannot change anything in HTML, just in jQuery.

This was enough:
var updateprice = $("#select_21 option:selected").attr('price');
added in :
while (i--) {
if (qty >= tierPrices[i]['price_qty']) {
var updateprice = $("#select_21 option:selected").attr('price');
var calc_price = tierPrices[i]['price'] * qty + (updateprice*qty);
return (calc_price).toFixed(2)
}
}

Related

Recalculating price in JS after redeeming 20% voucher

Trying to recalculate the final price in JS after applying a discount, but doesn’t seem to work. Total Cart and Redeem Coupon function just fine, but I can’t get the final price.
// TOTAL CART
obj.totalCart = function () {
var totalCart = 0;
for (var item in cart) {
totalCart += cart[item].price * cart[item].count;
} return Number(totalCart.toFixed(2));
}
// REDEEM COUPON
function validate(discount) {
var disc = "WE56DQ1";
var coupon = disc.trim();
var input = document.getElementById('discount').value;
if (input.toUpperCase() == coupon.toUpperCase()) {
document.getElementById('message').innerHTML = "Discount applied!";
document.getElementById('err').innerHTML = "";
return true;
} else {
document.getElementById('err').innerHTML = "Invalid discount";
document.getElementById('message').innerHTML = "";
return false;
}
}
// FINAL PRICE AFTER COUPON
obj.totalPrice = function () {
var discount = 20;
return totalPrice = totalCart - (totalCart * discount / 100);
}
To do this you could simply try:
newprice = Math.floor((oldprice/10)*80)
or
newprice = Math.floor((oldprice/100)*(100-discount))
Thanks for taking the time to make a post.
However, if you are planning to make this into a shop, it would be best to do all of the calculations on the server unless the js is server-side.

Solve mathematical function in javascript

I have created this function for a shopping basket. To be simple, i have x products with (2 checkbox + quantity input) for each.
The first checkbox add +3, second +8, to the product price. It's like (3+8+price)*quantity. At the end of the page, i have the total result (like product1 + product2...Etc)
The problem is: If i'm posting the form with new quantities, and going back to the page, i have the default result (total price) (of course, checkbox are checked + new quantity with PHP).
Here is my function:
$(function(){
var item_prices = 0;
var total_item_prices = 0;
var total_unique_item_prices = 0;
var total_price = 0;
$.each($('*[data-item-price]'), function(index, element) {
var item_price = $(element).data("item-price");
total_unique_item_prices = parseInt($('[data-total]').html()) + item_price;
total_price = total_unique_item_prices;
$('[data-total]').html(total_unique_item_prices);
})
$.each($('*[data-item-price]'), function(index, element) {
var item_price = $(element).data("item-price");
var price_of_options = 0;
var quantity = parseInt($(element).find('input[data-quantity]').val());
$.each($(element).children().find("[data-price]"), function(index, element2) {
$(element2).click(function(){
var actual_price = parseInt($('[data-total]').html());
var actual_item_price = parseInt($(element).find('[data-item-total]').html());
var price = $(element2).data("price");
if ($(element2).is(':checkbox') && $(element2).is(':checked')) {
price_of_options += price;
$(element).find('[data-item-total]').html(actual_item_price + (price * quantity));
$('[data-total]').html(actual_price + (price * quantity));
}
else {
price_of_options -= price;
$(element).find('[data-item-total]').html(actual_item_price - (price));
$('[data-total]').html(actual_price - (price * quantity));
}
})
})
$(element).find('input[data-quantity]').bind('keyup mouseup', function () {
var new_quantity = parseInt($(element).find('input[data-quantity]').val());
var quantity_dif = new_quantity - quantity;
var actual_price = parseInt($('[data-total]').html());
if (quantity_dif > 0) {
quantity_dif = new_quantity - quantity;
$(element).find('[data-item-total]').html((item_price + price_of_options) * new_quantity);
$('[data-total]').html(actual_price + ((item_price + price_of_options) * quantity_dif));
}
else {
quantity_dif *= -1;
quantity = parseInt($(element).find('[data-quantity]').val());
$(element).find('[data-item-total]').html((item_price + price_of_options) * new_quantity);
$('[data-total]').html(actual_price - ((item_price + price_of_options) * quantity_dif));
}
quantity = parseInt($(element).find('[data-quantity]').val());
})
})
})
As I said, code is working: https://jsfiddle.net/redbean/4dy38ye4/1/ Just not when i'm reloading the webpage.
I'm not english, be kind about this. I'm trying to do the best to be clear!

Value condition not working as expected

I have number of inputs and I want to set a minimum value of each input section. For example, I have set a minimum input value of 100. So if the value of any input is less than 100 from all the inputs it will show an error. Otherwise if value of all the inputs is greater than or equal to 100 it will show the success message.
In my case if I enter less than value in an input it will show error but with this less value if I enter greater value in other input it show success message.
<div class="color-quantity not-selected-inputs selected-input-wrap">
<input type="text" class="custom_small" name="custom_small" onkeydown="return myFunction(event);">
</div>
<div class="color-quantity not-selected-inputs selected-input-wrap">
<input type="text" class="custom_medium" name="custom_medium" onkeydown="return myFunction(event);">
</div>
<input type="text" class="custom_large" name="custom_large" onkeydown="return myFunction(event);">
</div>
jQuery('.selected-input-wrap > input').map(function () {
var total = 0;
jQuery('input', this).each(function () {
total += this.value * 1;
});
if (parseInt(total) <= 99) {
jQuery(".select-quantity").html('<p>Please select at least 100 for each color</p>');
} else if (parseInt(total) >= 100) {
jQuery(".select-quantity").html('<p>Success</p>');
}
Please have a look at the code and help me find out the issue
There's a couple of issues.
You should declare total outside the loop otherwise you reset it back to 0 on each iteration.
You should also use a single each() call to loop over a set of elements, as map() is intended to be used to create an array from those elements.
You only need to call parseInt() once when you add the value to total
Your else if condition is redundant and can be replaced by just else, or even a ternary as below.
Try this:
jQuery(function($) {
var total = 0;
$('.selected-input-wrap > input').each(function () {
total += parseInt(this.value, 10);
});
var msg = total >= 100 ? '<p>Success</p>' : '<p>Please select at least 100 for each color</p>';
$(".select-quantity").html(msg);
});
The total variable is looping through all the inputs and only once its returning according to your code. Try closing the each loop after the if-else condition and check once.
jQuery('.selected-input-wrap > input').map(function () {
var total = 0;
jQuery('input', this).each(function () {
total += this.value * 1;
if (parseInt(total) <= 99) {
jQuery(".select-quantity").html('<p>Please select at least 100 for each color</p>');
} else if (parseInt(total) >= 100) {
jQuery(".select-quantity").html('<p>Success</p>');
}
});
})
You can use the following jquery code :-
jQuery('.selected-input-wrap > input').map(function () {
var total = 0;
jQuery('input').each(function () {
total = $(this).val();
if (parseInt(total) <= 99) {
jQuery(".select-quantity").html('<p>Please select at least 100 for each color</p>');
}
else if (parseInt(total) >= 100) {
jQuery(".select-quantity").html('<p>Success</p>');
}
});
});
It may help you.
Try this.
var MIN = 100, value = 0;
jQuery('.selected-input-wrap > input').each(function (idx,el) {
value += parseInt(el.value);
});
if (value < MIN) {
jQuery(".select-quantity").html('<p>Please select at least 100 for each color</p>');
} else {
jQuery(".select-quantity").html('<p>Success</p>');
}
In My Case i have solved the issue as follows:
var total = 0;
var array_total = new Array();
jQuery('.selected-input-wrap > input').each(function(index, value) {
jQuery( ".right-minimu").remove();
var total = jQuery(this).val();
console.log("Total Value : " + total);
if (total != '') {
var t_array = array_total.push(total);
}
console.log('Total Array : ' + array_total);
});
/******** make array unique *************/
var unique_total = [];
jQuery.each(array_total, function(i, el) {
if (jQuery.inArray(el, unique_total) === -1)
unique_total.push(el);
});
var current_urls = jQuery(location).attr('href');
var rest = current_urls.substr(37, 9); //
var current_urls = jQuery(location).attr('href');
var rest_2 = current_urls.substr(37, 18);
var rest_3 = current_urls.substr(37, 15);
var rest_4 = current_urls.substr(37, 8);
jQuery.each(unique_total, function(key, total) {
for (var i = 0; i <= unique_total.length; i++) {
if(rest == "bracelets") {
if (parseInt(unique_total[i]) <= 99) {
jQuery(".select-quantity").css("display", "block");
jQuery(".select-quantity").html('<p>Please select at least 100 for each color</p>');
jQuery( "#order-overview-table table" ).css("display" , "none") ;
jQuery( "#order-overview-table").append("<p class='right-minimu'>Please select at least 100 for each color</p>") ;
jQuery('.btn-cart').removeAttr("onclick");
return false;
} else if (parseInt(unique_total[i]) >= 100) {
jQuery(".select-quantity").css("display", "none");
jQuery('.btn-cart').attr('onClick', 'productAddToCartForm.submit(this);');
jQuery(".select-quantity").html('<p>Products Added</p>').delay(4000);
}
}

jQuery updating function with input change from JS

I have a few functions and events in place that update invoice totals on change, paste, keyup and touchend which works great. However I have coded something that allows you to insert item data from a dropdown select and copies some things to input values however that does not update and now sure what changes I need to make for this to happen. Anyone have any ideas?
JSFiddle: http://jsfiddle.net/9m7q0mp8/ (if you click select product and add your see what I mean, it adds name and value, but I need it to update the subtotal and also the totals at bottom like it does, when you manually enter values in for an item).
JS:
$(document).on('click', ".item-select", function(e) {
e.preventDefault;
var product = $(this);
$('#insert').modal({ backdrop: 'static', keyboard: false }).one('click', '#selected', function(e) {
var itemText = $('#insert').find("option:selected").text();
var itemValue = $('#insert').find("option:selected").val();
$(product).closest('tr').find('#invoice_product').val(itemText);
$(product).closest('tr').find('#invoice_product_price').val(itemValue);
//updateTotals('#invoice_table');
//calculateTotal();
});
return false;
});
// add new product row on invoice
var cloned = $('#invoice_table tr:last').clone();
$(".add-row").click(function(e) {
e.preventDefault();
cloned.clone().appendTo('#invoice_table');
});
calculateTotal();
$('#invoice_table').on('change keyup paste touchend', '.calculate', function() {
updateTotals(this);
calculateTotal();
});
$('#invoice_totals').on('change keyup paste touchend', '.calculate', function() {
calculateTotal();
});
function updateTotals(elem) {
var tr = $(elem).closest('tr'),
quantity = $('[name="invoice_product_qty[]"]', tr).val(),
price = $('[name="invoice_product_price[]"]', tr).val(),
isPercent = $('[name="invoice_product_discount[]"]', tr).val().indexOf('%') > -1,
percent = $.trim($('[name="invoice_product_discount[]"]', tr).val().replace('%', '')),
subtotal = parseInt(quantity) * parseFloat(price);
if(percent && $.isNumeric(percent) && percent !== 0) {
if(isPercent){
subtotal = subtotal - ((parseFloat(percent) / 100) * subtotal);
} else {
subtotal = subtotal - parseFloat(percent);
}
} else {
$('[name="invoice_product_discount[]"]', tr).val('');
}
$('.calculate-sub', tr).val(subtotal.toFixed(2));
}
function calculateTotal() {
var grandTotal = 0,
disc = 0,
c_ship = parseInt($('.calculate.shipping').val()) || 0;
$('#invoice_table tbody tr').each(function() {
var c_sbt = $('.calculate-sub', this).val(),
quantity = $('[name="invoice_product_qty[]"]', this).val(),
price = $('[name="invoice_product_price[]"]', this).val() || 0,
subtotal = parseInt(quantity) * parseFloat(price);
grandTotal += parseFloat(c_sbt);
disc += subtotal - parseFloat(c_sbt);
});
// VAT, DISCOUNT, SHIPPING, TOTAL, SUBTOTAL:
var subT = parseFloat(grandTotal),
finalTotal = parseFloat(grandTotal + c_ship),
vat = parseInt($('.invoice-vat').attr('data-vat-rate'));
$('.invoice-sub-total').text(subT.toFixed(2));
$('#invoice_subtotal').val(subT.toFixed(2));
$('.invoice-discount').text(disc.toFixed(2));
$('#invoice_discount').val(disc.toFixed(2));
if($('.invoice-vat').attr('data-enable-vat') === '1') {
if($('.invoice-vat').attr('data-vat-method') === '1') {
$('.invoice-vat').text(((vat / 100) * subT).toFixed(2));
$('#invoice_vat').val(((vat / 100) * subT).toFixed(2));
$('.invoice-total').text((finalTotal).toFixed(2));
$('#invoice_total').val((finalTotal).toFixed(2));
} else {
$('.invoice-vat').text(((vat / 100) * subT).toFixed(2));
$('#invoice_vat').val(((vat / 100) * subT).toFixed(2));
$('.invoice-total').text((finalTotal + ((vat / 100) * finalTotal)).toFixed(2));
$('#invoice_total').val((finalTotal + ((vat / 100) * finalTotal)).toFixed(2));
}
} else {
$('.invoice-total').text((finalTotal).toFixed(2));
$('#invoice_total').val((finalTotal).toFixed(2));
}
}
JSFIDDLE
The id problem is that it must be unique, this will not the solve problem but will prevent others, it an HTML rule (W3SCHOOLS Id description):
The id attribute specifies a unique id for an HTML element (the value
must be unique within the HTML document).
The id attribute is most used to point to a style in a style sheet, and by JavaScript (via the HTML DOM) to manipulate the element with the specific id.
The input event should contain all the other events that you have listed alone, with some difference (input event answer):
Occurs when the text content of an element is changed through the user
interface.
This was another problem: e.preventDefault;, you missed the parenthesis:e.preventDefault();
The real problem was that updateTotals(); was sending the wrong element identifier, this is the correct one:updateTotals('.calculate');
$(document).on('click', ".item-select", function (e) {
e.preventDefault();
var product = $(this);
$('#insert').modal({backdrop: 'static',keyboard: false}).one('click', '#selected', function (e) {
var itemText = $('#insert').find("option:selected").text();
var itemValue = $('#insert').find("option:selected").val();
$(product).closest('tr').find('#invoice_product').val(itemText);
$(product).closest('tr').find('#invoice_product_price').val(itemValue);
updateTotals('.calculate');
calculateTotal();
});
return false;
});

using jquery to sum the text box value in the child repeater control and show the total in the label in footer

I am trying this code for in jquery to sum the text box value in the child repeater control and show the total in the label in footer. I get null is null or not an object error.
function display(objSecName) {
var objsec = objSecName;
// var lablTotAmount = document.getElementById(objSecName);
alert(objsec);
$('.totamt input[type=text]').each(function () {
$(this).change(function () {
alert(calsum());
});
});
function calsum() {
var Total = 0;
var limtamt = 120000;
$('.totamt input[type=text]').each(function () {
if (!isNaN(this.value) && this.value.length != 0) {
Total += parseFloat($(this).val());
document.getElementById(lblTotalAmountId80C).value = Total;
}
});
return Total;
};
}
Hmm, you should try to limit your code a bit when posting here.
I cleared it up a bit for you.
Most likely the isNaN is a bit annoying in this case, I replaced that with the jquery-variant isNumeric.
function display(objSecName) {
$('.totamt input[type=text]').change(function () {
alert(calsum());
});
function calsum() {
var total = 0;
$('.totamt input[type=text]').each(function () {
var value = parseFloat(this.value);
if ($.isNumeric(value)) {
total += value;
}
});
document.getElementById(lblTotalAmountId80C).value = total;
return total;
};
}

Categories