jQuery updating function with input change from JS - javascript

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

Related

Update price on change inlcuding on select

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

calculate total price from checkbox + select list

i want to calculate the total price from select list + checkboxes
this code showing the price of selected element from the list "tvs":
<script type="text/javascript">
$(document).ready(function () {
var cheap = false;
$('#tvs').change(function () {
var price = parseFloat($('.total').data('base-price')) || 0;
$('#tvs').each(function (i, el) {
price += parseFloat($('option:selected', el).data(cheap ? 'cheap' : 'price'));
console.log('x', price)
$('.total').val(price.toFixed(2) + '' + '$');
});
});
});
</script>
<input placeholder="0.00$" style=" width: 65px; border: 0px;" class="total" data-base-price="0" readOnly>
and this code showing the price of checked checkboxes:
<script type="text/javascript">
function update_amounts_modal() {
var sum = 0.0;
$('form').each(function () {
var qty = $(this).find('.qty').val();
var price = $(this).find('.price').val();
var isChecked = $(this).find('.idRow').prop("checked");
if (isChecked){
qty = parseInt(qty, 10) || 0;
price = parseFloat(price) || 0;
var amount = (qty * price);
sum += amount;
}
});
$('.total-modal').text(sum.toFixed(2) + ' ' + '$');
$().ready(function () {
update_amounts_modal();
$('form .qty, form .idRow').change(function () {
update_amounts_modal();
});
});
</script>
<div id="subusers" class="total-modal">0.00 $</div>
Hey #musa94 I assume you have a fairly large application and you separate your code into files and what to find a way to sum up two values from different chunks of code. A easy way without changing too much of your existing code is to define a shared data object that holds the values that you want to handle through out your application. You can sum the value from the list and checkbox up by accessing the values in the data object.
// define a data object that exists in your application
window.__ = window.__ || { data: { total: 0, modal: 0 } };
$(document).ready(function () {
var cheap = false;
$('#tvs').change(function () {
var total = getTvsTotal(cheap);
// update your view
$('.total').val(total.toFixed(2) + '' + '$');
// update your data object
__.data.total = total;
console.log('review data object', __);
});
});
$(document).ready(function () {
$('form .qty, form .idRow').change(function () {
var total = update_amounts_modal();
$('.total-modal').text(total.toFixed(2) + ' ' + '$');
__.data.modal = total;
console.log('review data object', __);
});
});
/**
* calculate your tvs total
* #param {boolean}
* #return {number}
*/
function getTvsTotal(cheap) {
var price = parseFloat($('.total').data('base-price')) || 0;
$('#tvs').each(function (i, el) {
price += parseFloat($('option:selected', el).data(cheap ? 'cheap' : 'price'));
console.log('list total:', price);
});
return price;
}
/**
* calculate your amounts modal
* #return {number}
*/
function update_amounts_modal() {
var sum = 0.0;
$('form').each(function () {
var qty = $(this).find('.qty').val();
var price = $(this).find('.price').val();
var isChecked = $(this).find('.idRow').prop("checked");
var amount;
if (isChecked){
qty = parseInt(qty, 10) || 0;
price = parseFloat(price) || 0;
amount = qty * price;
sum += amount;
}
console.log('sum:', sum);
});
return sum;
}

updated values inside form do not transfer properly into new div

basically when you enter a value out of the specified range it gets updated to the minimum/maximum allowed, but the value of the var doesn't get updated to the max/min. (you can check by entering 1 into both forms and clicking on quote)
https://jsfiddle.net/epf4uyr6/
function cadCheck(input) {
if (input.value < 2) input.value = 2;
if (input.value >= 100) input.value = 99.99;
}
document.getElementById('cad').onkeyup = function() {
var cad = (this.value);
document.getElementById("cad-quote").innerHTML = "Market: $" +cad;
}
your values not updating properly because , keyup function executing first and then onchange(cadCheck) function execute.
your current logic is inside onchange function , thats why value not updating properly.
move this line in onkeyup function , and remove it from onchange.
document.getElementById('cad').onkeyup = function() {
if (this.value >= 100) this.value = 99.99;
var cad = (this.value);
document.getElementById("cad-quote").innerHTML = "Market: $" +cad;
}

Some basic Javascript to suggest a pricing

I have code that currently will give a DayPrice, an ExtraDayPrice and a WeekPrice based on the ItemValue that was entered by the user.
$("#ItemValue").change(function () {
var val = parseFloat($(this).val());
if (!isNaN(val)) {
$("#Price").val(getPriceString(val * 0.02));
$("#ExtraDayPrice").val(getPriceString(val * 0.015));
$('#WeekPrice').val(getPriceString(val * 0.1));
}
});
Now instead, I'd like the ExtraDayPrice and WeekPrice to be depending on the DayPrice (which in turn is still depending on the entered ItemValue). It must be like this: ExtraDayPrice = 0,75 * DayPrice. WeekPrice = 5,3 * DayPrice.
How do I do this?
Thanks in advance!
You should use variables, assign those variables some value and then set the value of the input field to those variables. And since you need to update the other prices if the user wants to change the price manually you can use one change function, but just adjust the value used to calculate the other pricing fields.
$("#ItemValue, #Price").change(function () {
var val = parseFloat($(this).val());
if (!isNaN(val)) {
//if the element clicked is ItemValue adjust val to be suggested dayPrice
if(this.id == "ItemValue") {
val *= 0.02;
}
//update the pricing elements
updatePricing(val);
}
});
function updatePricing(dayPrice) {
var extraDayPrice = dayPrice * 0.015;
var weekPrice = dayPrice * 0.1;
$("#Price").val(getPriceString(dayPrice));
$("#ExtraDayPrice").val(getPriceString(extraDayPrice));
$('#WeekPrice').val(getPriceString(weekPrice));
}

jQuery price calculator function is not working with tabs

I have been trying to get this working from last couple of days without any success. I have this price calculator function developed by a freelancer who is not reachable from last few weeks.
This function works fine without any JavaScript tabs but not quite right with them. I need to have tabs on page because there are tons of options in this calculator.
This is the jQuery function.
$(document).ready(function() {
// For tabs
var tabContents = $(".tab_content").hide(),
tabs = $("ul.nav-tabs li");
tabs.first().addClass("active").show();
tabContents.first().show();
tabs.click(function() {
var $this = $(this),
activeTab = $this.find('a').attr('href');
if (!$this.hasClass('active')) {
$this.addClass('active').siblings().removeClass('active');
tabContents.hide().filter(activeTab).fadeIn();
}
return false;
});
// 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)) {
$('#cost_calc_total_cost').html(messageHTML);
$('.addons-box').hide();
} else {
$('#cost_calc_total_cost').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() {
if ($(this).is(':hidden')) {
$(this).removeClass('cost_calc_active');
}
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();
});
You can see this working on jsfiddle without tabs. I can select options from multiple sections and order box will update selected option's price and details dynamically.
But when I add JavaScript tabs, it stop working correctly. See here. Now if I select option from different sections, order box resets previous selection and shows new one only.
I think the problem is with calculator somewhere.
You are removing the active class from hidden elements. This means that when you move to the second tab you disregard what you've done in the first.
line 120 in your fiddle:
if ($(this).is(':hidden')) {
$(this).removeClass('cost_calc_active');
}
I haven't taken the code in depth enough to tell if you can just remove this.

Categories