My variable refused to display in my Div - javascript

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.

Related

Change quantity to 3 decimals and update price on change

In my store, I have fruits product which I want to sell the quantity based on kg and grams (1.000 = 1kg, 0.500 = 0.5kg or 500grams, etc.) currently is on 1,2,3,4. This is my code ( Shopify, Jquery )
jQuery(".button").on("click", function() {
var oldValue = jQuery("#quantity").val(),
newVal = 1;
if (jQuery(this).text() == "+") {
newVal = parseInt(oldValue) + 1;
} else if (oldValue > 1) {
newVal = parseInt(oldValue) - 1;
}
jQuery(".product-single #quantity").val(newVal);
{% if settings.display_subtotal %}
updatePricing();
{% endif %}
});
{% if settings.display_subtotal %}
//update price when changing quantity
function updatePricing() {
//try pattern one before pattern 2
var regex = /([0-9]+[.|,][0-9]+[.|,][0-9]+)/g;
var unitPriceTextMatch = jQuery('.product-single #ProductPrice').text().match(regex);
if (!unitPriceTextMatch) {
regex = /([0-9]+[.|,][0-9]+)/g;
unitPriceTextMatch = jQuery('.product-single #ProductPrice').text().match(regex);
}
if (unitPriceTextMatch) {
var unitPriceText = unitPriceTextMatch[0];
var unitPrice = unitPriceText.replace(/[.|,]/g,'');
var quantity = parseInt(jQuery('.product-single #quantity').val());
var totalPrice = unitPrice * quantity;
var totalPriceText = Shopify.formatMoney(totalPrice, window.money_format);
regex = /([0-9]+[.|,][0-9]+[.|,][0-9]+)/g;
if (!totalPriceText.match(regex)) {
regex = /([0-9]+[.|,][0-9]+)/g;
}
totalPriceText = totalPriceText.match(regex)[0];
var regInput = new RegExp(unitPriceText, "g");
var totalPriceHtml = jQuery('.product-single #ProductPrice').html().replace(regInput ,totalPriceText);
jQuery('.product-single .total-price span').html(totalPriceHtml);
}
}
jQuery('.product-single #quantity').on('change', updatePricing);
{% endif %}
var t = false
jQuery('input').focus(function () {
var $this = jQuery(this)
t = setInterval(
function () {
if (($this.val() < 1 ) && $this.val().length != 0) {
if ($this.val() < 1) {
$this.val(1)
}
jQuery('.min-qty-alert').fadeIn(1000, function () {
jQuery(this).fadeOut(500)
})
}
}, 50)
})
jQuery('input').blur(function () {
if (t != false) {
window.clearInterval(t)
t = false;
}
})
So let's say the price is 4$ for kg, for 200g (on quantity field 0.200) so the total price should update whatever is 200g of 4$. I just need this, so anyone who can help me/give me an idea, I'll be grateful

How can I calculate the total value of amount due after choosing different option from drop-down list?

I tried some codes, but none worked. I have an amount due that should change when the quantity number from the drop-down list changes. So if someone changes the number of order it should multiply by the base number of desktop and the result should be the total amount. Here is part of my code which I think is relative to calculation part.
var amountDue = document.getElementById("amountDue");
var desktopAddOns = document.querySelectorAll(".products");
var total = 0;
var price = 0;
//Removes the add on options from view
document.getElementById("desktops").onchange = function () {
if (document.getElementById("desktops").checked) {
price = 185;
} else if (document.getElementById("desktops").checked == false) {
price = 185;
removeAddOns(price);
}
addAddOns(price);
};
computerType.onchange = function () {
document.getElementById("desktops").checked = false;
};
function addAddOns(price) {
total += price;
amountDue.innerHTML = total;
}
function removeAddOns(price) {
total -= price * 2;
amountDue.innerHTML = total;
}
<div class=" products">
<div class="form-group">
<label for="chkYes1">
<input type="checkbox" id="desktops" name="" value="desktops" />
desktop $185.00
</label>
</div>
<select id="selectbasic" name="" class="">
<option value="1">0</option>
<option value="2">1</option>
<option value="3">2</option>
</select>
</div>
<div class="form-group border border-dark rounded py-3 px-5">
<h3>Amount Due: <p id="amountDue">0</p>
</h3>
</div>
I have found a solution:
First, remove this code snippet since it's currently throwing an error:
computerType.onchange = function () {
document.getElementById("desktops").checked = false;
};
Second, declare these two variables to store the <select> tag element & the future selected value like so:
var selectOptions = document.getElementById("ddlViewBy");
var selectedValue;
Third, add this method to get the selected value & multiply the total like so:
selectOptions.addEventListener('change', () => {
selectedValue = selectOptions.options[ selectOptions.selectedIndex].value;
amountDue.innerHTML = Math.round(total * selectedValue);
})
For your reference, here is the full code sample:
var amountDue = document.getElementById("amountDue");
var desktopAddOns = document.querySelectorAll(".products");
var selectOptions = document.getElementById("selectbasic");
var selectedValue;
var total = 0;
var price = 0;
//Removes the add on options from view
document.getElementById("desktops").onchange = function () {
if (document.getElementById("desktops").checked) {
price = 185;
} else if (document.getElementById("desktops").checked == false) {
price = 185;
removeAddOns(price);
}
addAddOns(price);
};
//amountDue.innerHTML += total;
function addAddOns(price) {
total += price;
amountDue.innerHTML = total;
}
function removeAddOns(price) {
total -= price * 2;
amountDue.innerHTML = total;
}
selectOptions.addEventListener('change', () => {
selectedValue = selectOptions.options[ selectOptions.selectedIndex].value;
amountDue.innerHTML = Math.round(total * selectedValue);
})
You can also check this working code sample.
If you have questions about the code, let me know.

After click the select option update product price shows wrong in opencart

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

Update dynamically generated price of two boxes with select option

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

Javascript select switch select on change

I have 2 selects, one switch the other while changing
<select class="select-global-132" name="tipo" id="tipo" onchange="tipo_cambio()">
<option value="Digital" selected>Seleccionar</option>
<option value="Boleta">Boleta</option>
<option value="Factura">Factura</option>
<option value="Traslado">Guia de Despacho</option>
</select>
and number two
<select style="display:none;" name="iva" id="iva" >
<option value="0" selected>No</option>
<option value="19">Aplicar 19%</option>
</select>
The javascript that does the trick set TAXES while option 2 or 3 in first select but I just added a new option and it must NOT add taxes but it does anyway
A way to try to fix it is the follow
function tipo_cambio () {
var tipo = document.getElementsByName('tipo')[0];
if ( tipo.value == "Digital")
if ( tipo.value == "Traslado")
taxes.selectedIndex = 0;
else taxes.selectedIndex = 1;
but it is not really working it add taxes anyway. I need it to NOT set taxes 19% when set to first or last option but apply the taxes (switch the other select) with options 2 and 3 only
The problem is here but I am not good with javascript
if ( tipo.value == "Digital")
if ( tipo.value == "Traslado")
any idea?
Here the entire javascript code
var taxes = document.getElementsByName('iva')[0];
var discount = document.getElementsByName('descuento')[0];
var cost = document.getElementsByName('neto')[0];
var price = document.getElementsByName('preciodesc')[0];
var tneto = document.getElementsByName('totalneto')[0];
var ttaxes = document.getElementsByName('ivaunitario')[0];
var ivatot = document.getElementsByName('ivatotal')[0];
var total = document.getElementsByName('subtotal')[0];
var quantity = document.getElementsByName('cantidad')[0];
var ttp = document.getElementsByName('total')[0];
var micosto = document.getElementsByName('costo')[0];
var costotot = document.getElementsByName('costototal')[0];
var migan = document.getElementsByName('ganancia')[0];
var gantot = document.getElementsByName('gananciatotal')[0];
function updateInput() {
price.value = cost.value - (cost.value * (discount.value / 100));
ttaxes.value = (price.value * (taxes.value / 100));
ivatot.value = parseFloat(ttaxes.value) * parseFloat(quantity.value);
costotot.value = parseFloat(micosto.value) * parseFloat(quantity.value);
migan.value = parseFloat(price.value) - parseFloat(micosto.value);
gantot.value = parseFloat(migan.value) * parseFloat(quantity.value);
tneto.value = parseFloat(price.value) * parseFloat(quantity.value);
var sum = parseFloat(price.value) + parseFloat(ttaxes.value);
total.value = sum.toFixed(0);
ttp.value = sum.toFixed(0) * quantity.value;
}
taxes.addEventListener('change', updateInput);
discount.addEventListener('change', updateInput);
cost.addEventListener('change', updateInput);
cost.addEventListener('keyup', updateInput);
quantity.addEventListener('keyup', updateInput);
function tipo_cambio () {
var tipo = document.getElementsByName('tipo')[0];
if ( tipo.value == "Digital")
if ( tipo.value == "Traslado")
taxes.selectedIndex = 0;
else taxes.selectedIndex = 1;
updateInput();
}
Try this.. maybe this can help you.. you can use jquery for now
function tipo_cambio () {
var tipo = $('#tipo').val();
if ( $('#tipo').val() == "Digital"){
}else if ( $('#tipo').val() == "Traslado"){
$('#iva').show();
$('#iva').val(19);
}else {
$('#iva').val(0);
updateInput();
}
}
Example JSFIDDLE
As mentioned in comments, the error was with the if statement not performing as intended by the developer. The solution: use an or operator
if (tipo.value === "Digital" || tipo.value === "Traslado")

Categories