I have a checkout page, where I would like to implement a new feature: subtract from total cart value a certain amount, introduced in an input.
Example: There is 1 item in cart, with value of 10.00$. If user typed 100 in that input, then he would have a discount of 1$ (100 pts = 1$ in this example) and the final value of the cart would be 9.00$. Since I'm using some integrated apps for getting/calculating item value, total cart value, etc. I would like to get some generic code, which I would eventually adjust, to link with my existing code, functions, etc.
The function I have should have these features:
create form
get input value
subtract used points from user's total amount (for example totalPts = 1000)
subtract from cart total value used points, converted into $ (100pts = 1$)
For now, my function looks like this:
function appendRefferalPoints() {
const totalPts = 1000;
// creating form - ok
$form = $('<form id="refForm" class="coupon-form" action></form>');
$form.append(
'<input type="text" id="refValue" name="refInput" class="coupon-value input-small" >'
);
$form.append('<button type="submit" class="btn">Aplica</button>');
$("body").append($form);
// get input value - not ok
$("#refForm").submit(function () {
let value = 0;
$.each($("#refForm").serializeArray(), function (i, field) {
value[field.name] = field.value;
});
});
// subtraction from totalPts logic - not ok
let rez = totalPts - value;
console.log("Final Rez: " + rez);
// subtraction converted pts from cart value logic
}
Now when I submit the form I only url changes from /checkout#/cart to /checkout/?refInput=512#/cart
function appendRefferalPoints() {
const totalPts = 1000;
let cartValue=10;
let discount=0;
let inputValue = 0;
// creating form - ok
$form = $('<form id="refForm" class="refForm coupon-form" ></form>');
$form.append(
'<input type="text" id="refValue" name="refInput" class="coupon-value input-small" value="100" >'
);
$form.append('<button id="btnClick" class="btn">Aplica</button>');
$("body").append($form);
$(document).on("submit", "#refForm", function(e){
//getting input value while submitting form
inputValue=$("#refValue").val();
//converting 100 pts to 1 dallor
discount=inputValue/100;
//calculating balance pts
let balancePts = totalPts - parseInt(inputValue);
//calculating final amount
let finalCartValue=cartValue-discount;
alert("finalCartValue"+finalCartValue);
});
}
appendRefferalPoints();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
Related
I want to calculate 2 options from different selects in HTML and display the result in an input field. The first select will fill from a mysql database, the second select will fill with 1 option that is the pair of the first. I want to multiply them and display the result in the last input field. Here is an example:
The table of the database the field are "id product"-id quantity price type
table view
Here is the result that i want: to display
When the user selects the quantity the corresponding value is going to be displayed to the next field.
After that in the last input field i want to calculate the previous selections
the user can only select the quantity and not the price
I made a select with php and made an array which is converted to javascript array object
<?php
$sth = $conn->prepare("SELECT quantity,price FROM eb_products_price WHERE product_id = 20");
$sth->execute();
/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_GROUP);
$json_array = json_encode($result);
print_r($result);
With this code the only thing i can do is to display the quantity with a foreach
BUT the price will remain the last one and it wont change while i change the quantity.
I found a way to display the correct price but with javascript here is the code
<script>
var arrayObjects = {"400":["0.8"],"300":["0.9"],"200":["0.95"],"100":["1.1"]}
function products() {
var quantity= document.getElementById("quantity");
var price= document.getElementById("price");
var arrprice = quantity.options[quantity.selectedIndex].value;
while (price.options.length) {
price.remove(0);
}
var prices = arrayObjects[arrprice];
if (prices) {
var i;
for (i = 0; i < prices.length; i++) {
var price1 = new Option(prices[i], i);
price.options.add(price1);
}
}
}
</script>
Here is the calculate function that work without the last part of code:
calculate = function()
{
var quantity= document.getElementById('quantity').value;
var price= document.getElementById('price').value;
var number = parseFloat(quantity)*parseFloat(price);
var n = number.toFixed(2);
document.getElementById('result').value = n
}
To change a HTML-Element dynamically you need event Listeners like onChange example below:
var arrayObjects = {"400":["0.8"],"300":["0.9"],"200":["0.95"],"100":["1.1"]}
function products() {
var quantity = document.getElementById("quantity");
var factor = document.getElementById("factor"); // added
var price= document.getElementById("price");
// Fill dropdown (quantity)
while (quantity.options.length) {
quantity.remove(0);
}
// fill by key
for( var quantity_key in arrayObjects ) {
var quantity_option = new Option(
quantity_key,
quantity_key
);
quantity.options.add(quantity_option);
}
// onChange-Listener
quantity.onchange = () => {
factor.value = arrayObjects[quantity.value];
// look for factor by key in arrayObjects
price.value = Math.round(
quantity.value *arrayObjects[quantity.value]
);
};
}
products();
<select id='quantity'></select>
KG
<input type='text' id='factor' readonly="readonly">
<input type='text' id='price' readonly="readonly">
in javascript, to get the selected element (value) of a select, use :
var e = document.getElementById("quantity");
var quantity= e.options[e.selectedIndex].text;
I have the following fields on my form / web page with some fields that I would like to be calculated when a user types. (see image)
Fields - image here
The field Unit Cost is calculated by Case Cost / Case Size. I have that functioning perfectly with the following code
Casesize Textbox
#Html.TextBoxFor(model => model.q_supplierproduct.q_casesize, "{0:#.#}", new { #class = "calc" })
Case Cost Textbox
#Html.TextBoxFor(model => model.q_supplierproduct.q_casecost, "{0:#.#}", new { #class="calc"})
Unit Cost Textbox
#Html.TextBoxFor(model=> model.q_unitcost, "{0:#.#}", new { #class = "calc" })
Function
#* Calculate Unitcost value *#
<script>
var url = '#Url.Action("CalculateUnitCost", "CalculateValues")';
$('.calc').change(function () {
//get the values of the texboxes
var casecost = $('#q_supplierproduct_q_casecost').val();
var casesize = $('#q_supplierproduct_q_casesize').val();
//check if field entries are valid
if (casecost == '' || casesize == '' || isNaN(casecost) || isNaN(casesize)) { return; }
$.post(url, { Q_casecost: casecost, Q_casesize: casesize }, function (response) {
$('#q_unitcost').val(response);
});
});
</script>
Controller
public class CalculateValuesController : Controller
{
[HttpPost]
public JsonResult CalculateUnitCost(double Q_casecost, double Q_casesize)
{
var result = Computation.GetUnitCost(Q_casecost, Q_casesize);
return Json(result.ToString("#.#"));
}
Method
public class Computation
{
public static double GetUnitCost(double Q_casecost, double Q_casesize)
{
double unitcostresult = Q_casecost / Q_casesize;
return unitcostresult;
}
Just to mention again, this code works as expected, when I change the values in casesiez and casecost, the unitcost field updates accordingly. The next thing I wanted to achieve was to calculate the profit field based on a values entered in the price field minus unit cost field (which is a previously calculated field). I went on to add a second script for that field plus the respective calculations in the controller and method
See two scripts image
<script>
var url = '#Url.Action("CalculateProfit", "CalculateValues")';
$('.calc').change(function () {
//get the values of the texboxes
var sellprice = $('#q_sellprice').val();
var unitcost = $('#q_unitcost').val();
//check if field entries are valid
if (sellprice == '' || unitcost == '' || isNaN(sellprice) || isNaN(unitcost)) { return; }
$.post(url, { Q_sellprice: sellprice, Q_unitcost: unitcost }, function (response) {
$('#q_profit').val(response);
});
});
from this point onwards with this addition, unit cost field stops working (no update when data is entered), but profit field will calculate accordingly if I type values in unit cost and price field. (new scripts stops the first one from working as intended). What am I missing here?
Is it because of the common unit cost field in both scripts that causing the issue? How do I fix?
After reading the comments from Stephen and Tetsuya I changed the code to the following, and that solved my problem. The two fields unitcost and profit are updating now based on the respective changed fields. I do not call any action method here and I am doing all calculations in javascript as advised.
<script>
function calculate()
{
//Fields that are used for calculations
var casecost = parseFloat($('#q_supplierproduct_q_casecost').val());
var casesize = parseFloat($('#q_supplierproduct_q_casesize').val());
var price = parseFloat($('#q_sellprice').val());
//Calculations
var unitcost = casecost / casesize; // get unitcost from casecost FIELD and casesize FIELD
var profit = price - unitcost; // get profit from price FIELD and unicost CALCULATED value
//set results to the updating fields
$('#q_unitcost').val(unitcost.toFixed(2));
$('#q_profit').val(profit.toFixed(2));
}
$(document).ready(function () {
//calculate();
//calculate everytime these following fields change
$('#q_supplierproduct_q_casecost').change(calculate);
$('#q_supplierproduct_q_casesize').change(calculate);
$('#q_sellprice').change(calculate);
$(unitcost).change(calculate);
});
</script>
Hope this helps someone else down the road.
How to calculate using jquery or Javascript in Codeigniter as below requirement
I have 3 input element to calculate after user complete they form element :
1, Quantity
2, Unitprice
3, Total.
By Total = quantity * unitprice.
<td><?php echo form_input('quantity','',' class="form-control"')?></td>
<td><?php echo form_input('unitprice','',' class="unit form-control" placeholder="unit pricee"')?></td>
<td><?php echo form_label('','total','class="form_control"')?></td>
I try to write javascript like this
<script type="text/javascript">
$(document).ready(function () {
$('.unitprice').keyup(function () {
Calculate();
});
});
function Calculate() {
var quantity = document.getElementsByClassName("quantity").val();
var unitprice = document.getElementsByClassName("unitprice").val();
var total = quantity * unitprice;
$('.total').val(total);
}
</script>
But it is not work
Thanks advance!!!!
Try like this:
$(function(){
$('.qty, .unit').on('blur', function(e){
var qty = parseFloat( $('.qty').val() ),
unit = parseFloat( $('.unit').val() );
if( isNaN(qty) || isNaN(unit) ) {
$('.result').text('');
return false;
}
var total = qty * unit;
$('.result').text( total );
});
});
DEMO
Here's a basic example, since I was bored. Fiddle - http://jsfiddle.net/sgnl/44ts8ucf/1/
html
<input type="text" id="quantity" class="calc_element"> Quantity
<input type="text" id="unit_price" class="calc_element"> Unit Price
<div id="total"></div>
javascript
// get some IDs or classes on your elements to target them easily
var total = $('#total');
// bind an event that triggers on KEYUP
$('.calc_element').on('keyup', function(){
// when triggered get the values from the input elements
// via jQuery's '.val()' method
var quantity = $('#quantity').val() || 1;
var unit_price = $('#unit_price').val();
var result = (quantity * unit_price) + " total";
// set the innerHTML of the div to your calculated total
total.html(result);
});
YMMV, thats the jist of it, some tweaking will need to be down for your code.
I am trying to use Javascript to calculate sum of order in one big form. Each product has its own price, however, there are more prices tied with some products. Each product has it's own price, but if a customer orders bigger quantity of this product, the price will drop to a value that is specified in a database table.
To simplify, the shopping form for one item looks something like this.
<input name="id" value="'.$id.'" type="hidden">
<input name="price_'.$id.'" value="'.$price.'" type="hidden">
<input name="quantity_'.$id.'" type="text" onchange="calculateTotal()">
I have a table with the discounts: itemId, minimumQuantity, priceAfterDiscount. There can be more than one discounts connected with one item. The MySQL query works with LEFT JOIN of Items and Discounts tables.
calculateTotal() calculates the total of order after every input change.
What I would like to do, is to check if the quantity of certain product is greater than the value needed for the discounts and if so, I would like to change the value of the input with price from item's regular price to the discounted one. Then, calculateTotal() will use that price and update the total.
To do so, I think I can do something like adding more hidden inputs with values of all discounts. The function would check if there is a discount linked to every item and if so, it will check if the quantity is greater than requiredQuantity and if this condition is met, it will update the value of price hidden input. Please keep in mind that there can be multiple discounts connected to one item - the function should find the lowest price that meets requiredQuantity.
I am trying to do this - create the hidden inputs and somehow parse them in javascript, but I am just not able to figure this out. I tried my best to explain the problem, however, if my explanation is not sufficient, I will try to answer your questions regarding my issue.
I hope you are able and willing to help me. Thanks for help in advance.
Perhaps something like this example.
CSS
.itemLabel, .currentPrice, .subTotal {
display: inline-block;
width: 40px;
}
#myTotal {
border:2px solid red;
}
HTML
<fieldset id="myInputs"></fieldset>
<div id="myTotal"></div>
Javascript
var myInputs = document.getElementById('myInputs'),
myTotal = document.getElementById('myTotal'),
order = {
total: 0
},
items = {
foo: {
1: 0.5,
100: 0.25
},
bar: {
1: 1,
100: 0.5
}
},
totalNode;
function calculateTotal() {
var newTotalNode;
Object.keys(order).filter(function (key) {
return key !== 'total';
}).reduce(function (acc, key) {
order.total = acc + order[key].subTotal;
return order.total;
}, 0);
newTotalNode = document.createTextNode(order.total.toFixed(2));
if (totalNode) {
myTotal.replaceChild(newTotalNode, totalNode);
totalNode = newTotalNode;
} else {
totalNode = myTotal.appendChild(newTotalNode);
}
console.log(JSON.stringify(order));
}
calculateTotal();
Object.keys(items).forEach(function (key) {
var div = document.createElement('div'),
label = document.createElement('label'),
price = document.createElement('span'),
input = document.createElement('input'),
subtotal = document.createElement('span'),
priceNode,
subTotalNode;
order[key] = {
quantity: 0,
subTotal: 0,
price: items[key]['1']
};
priceNode = document.createTextNode(order[key].price.toFixed(2));
subTotalNode = document.createTextNode(order[key].subTotal.toFixed(2));
label.className = 'itemLabel';
label.setAttribute("for", key);
label.appendChild(document.createTextNode(key));
price.className = 'currentPrice';
price.id = key + 'CurrentPrice';
price.appendChild(priceNode);
input.id = key;
input.name = 'myFormGroup';
input.type = 'text';
input.addEventListener('change', (function (key, order, priceNode, subTotalNode) {
return function () {
var value = +(this.value),
newPriceNode,
newSubTotalNode;
Object.keys(items[key]).sort(function (a, b) {
return b - a;
}).some(function (quantity) {
if (value >= quantity) {
order.price = items[key][quantity];
newPriceNode = document.createTextNode(order.price.toFixed(2));
priceNode.parentNode.replaceChild(newPriceNode, priceNode);
priceNode = newPriceNode;
return true;
}
return false;
});
order.subTotal = order.price * value;
newSubTotalNode = document.createTextNode(order.subTotal.toFixed(2));
subTotalNode.parentNode.replaceChild(newSubTotalNode, subTotalNode);
subTotalNode = newSubTotalNode;
calculateTotal();
};
}(key, order[key], priceNode, subTotalNode)), false);
subtotal.className = 'subTotal';
subtotal.id = key + 'SubTotal';
subtotal.appendChild(subTotalNode);
div.appendChild(label);
div.appendChild(price);
div.appendChild(input);
div.appendChild(subtotal);
myInputs.appendChild(div);
});
On jsFiddle
I need to make a calculation in an asp.net page with the value from a usercontrol label.
the user control label is:
<asp:Label ID="LblInvoicePriceValue" runat="server" ></asp:Label>
I include it like this:
<Controls:VehicleInformation ID="VehicleInformationControl" runat="server" />
And my jquery function is something like:
Please see point 1 and 2.
<script type="text/javascript">
$(document).ready(function () {
alert('call function to do calculation here');
// 1. Find in the vehicle information user control the invoiced ammount label
// 2. Find the vat excluded value **after** it was typed in the textbox
// 3. If invoiced ammount is greater than zero, then
// 3.a Find Label Percentage
// 3.b Label.Text = (AmmountWithoutVat/InvoicedAmmount)*100 + '%'
});
</script>
HTML generated:UPdate1
For the label:
<span id="MainContent_VehicleInformationControl_LblInvoicePriceValue" class="bold"></span>
For the textbox:
<input name="ctl00$MainContent$TxtVatExcluded" type="text" id="TxtVatExcluded" class="calculation" />
Update 2:
<script type="text/javascript">
$(document).ready(function () {
alert('call function to do calculation here');
$("#TxtVatExcluded").keypress(function() {
var invoiceprice = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
var vatexcluced = $("#TxtVatExcluded").val();
var lblPercentage = $("#MainContent_LblPercentage");
if (invoiceprice > 0) {
lblPercentage.text((vatexcluced / invoiceprice) * 100);
}
})
// 1. Find in the vehicle information user control the invoiced ammount label
// 2. Find the vat excluded value after it was typed in the textbox
// 3. If invoiced ammount is greater than zero, then
// 3.a Find Label Percentage
// 3.b Label.Text = (AmmountWithoutVat/InvoicedAmmount)*100 + '%'
});
</script>
var label_text = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
$("#TxtVatExcluded").val(label_text);
UPDATE
If you want to check if the textfield is blank then only do copy the label then use following code
var label_text = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
var txt = $("#TxtVatExcluded").val();
if(txt.length==0)
{
$("#TxtVatExcluded").val(label_text);
}
You can use the rendered ID of the elements to get the values using jQuery
var lbl = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
var tbox = $("#TxtVatExcluded").val();
Later when the calculation is complet, you can update the label text as
$("#MainContent_VehicleInformationControl_LblInvoicePriceValue").html("new label");
Update:
To use the logic, where the user types, you have to bind the function to keypress/keyup/keydown event
$("#myinputbox").keypress(function() {
var lbl = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
var tbox = $("#TxtVatExcluded").val();
//... so on
}
Update 2:
Since, you are attempting to calculate with the values, it is safer to make sure, there are numbers in the first place. For that, you can use parseInt(), parseFloat() as needed.
$("#TxtVatExcluded").keypress(function() {
var invoiceprice = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
var vatexcluced = $("#TxtVatExcluded").val();
var lblPercentage = $("#MainContent_LblPercentage");
if (invoiceprice > 0) {
lblPercentage.text((parseInt(vatexcluced) / parseInt(invoiceprice)) * 100);
}
})
This will get you the value of the label control:
function Calculate()
{
var InvoicedAmmount = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
var AmmountWithoutVat = $("#TxtVatExcluded").val();
var Result = (AmmountWithoutVat/InvoicedAmmount)*100
$("#OutputLabel").html(Result + " %");
}
You can attach and onBlur event to your text box to fire your calculation when they leave the text box - you wouldn't really want to re-calculate the amount as they typed.
$(document).ready(function ()
{
$("#TxtVatExcluded").bind("blur",function(){ Calculate(); });
}