Calculate data to an input field from 2 select fields with javascript - javascript

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;

Related

Subtract amount on form submit JavaScript / JQuery

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>

Setting default values to appended text boxes using jQuery

I am looking to pass a list of autocomplete values to text boxes that have been appended based on a specified number of units.
function getUnits() {
var units = $("#units").val();
if (units > 1){
for (var count = 1; count < units-1; count++) {
$("<input type='text' /><br>").appendTo("#left-col");
}
$("#left-col").append('<input type="text">');
}}
$(function() {
google.script.run.withSuccessHandler(buildTagList)
.getAvailableTags();
});
function buildTagList(availableTags) {
$( '#med' ).autocomplete({
source: availableTags
});
}
This is the code for appending the appropriate amount of text boxes based on the # of units.
function getAvailableTags() {
var ss = SpreadsheetApp.openById("someID");
var s = ss.getSheetByName("someSheet");
var drug = s.getRange("A2:A").getValues();
var headers = 1;
var tagColumn = 0;
var availableTags = [];
for (var row=headers; row < drug.length; row++) {
availableTags.push(drug[row][tagColumn]);
}
return( availableTags );
}
I have tried creating the appended values with the same name/id/and class, but nothing seems to be working. A bonus question would also be: when a user goes to submit the form, how do I capture all of the appended boxes' values?
Here's a short example of adding textboxes to a dialog and submitting the data back to a spreadsheet
Run addTextBoxestoADialog(). Give it the names of the textboxes separated by forward slash. Like this: name1/name2/name3 and then it will build the form. You can fill in the values and hit submit and the names and values will be appended to the active sheet.
Code.gs:
function addTextBoxestoADialog() {
var ss=SpreadsheetApp.getActive();
var ui=SpreadsheetApp.getUi();
var resp=ui.prompt("Adding Text Boxes to a Dialog","Enter unique names of text boxes separate by forward slash /.",ui.ButtonSet.OK );
var tA=resp.getResponseText().split('/');
var html='<html><head><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"><script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>';
html+='<script>function fileUploadJs(frmData){google.script.run.upLoadForm(frmData);}</script></head><body>';
html+='<form id="myForm">';
for(var i=0;i<tA.length;i++) {
html+=Utilities.formatString('<br /><input type="text" value="%s" name="%s" /> %s',i+1,tA[i],tA[i]);//added default values
}
html+=Utilities.formatString('<input type="hidden" value="%s" name="NameArray" />',tA.join('~~~'));
html+='<br /><input type="button" value="Submit" onclick="fileUploadJs(this.parentNode)" />';
html+='</form></body></html>';
var userInterface=HtmlService.createHtmlOutput(html);
ui.showModelessDialog(userInterface, "Adding TextBoxes");
}
function upLoadForm(theForm) {
Logger.log(JSON.stringify(theForm));
var ss=SpreadsheetApp.getActive();
var sh=ss.getActiveSheet();
var nA=theForm.NameArray.split('~~~');
for(var i=0;i<nA.length;i++) {
sh.appendRow([nA[i],theForm[nA[i]]]);
}
}

Need text in input to not display user input once sent

Here is my jQuery, I have it working properly but once my row is added the user input in the inputs are still there and not cleared. How do I fix this?
// Removing menu rows
$('.menu-items').on('click', '.delete', function(){
$(this).closest('.menu-row').remove();
});
// HTML
var MENU_ROW_TEMPLATE = '<div class="menu-row"><span class="item-description">$description</span><div class="control-items"><span class="item-price">$price</span><span class="delete">X</span></div></div>'
// Adding menu rows
$('.menu-category').on('click', 'button', function(){
var $row = $(this).closest('.add-item');
var name = $row.find('input').first().val();
var price = $row.find('input').last().val();
var newRowHtml = MENU_ROW_TEMPLATE.replace('$description', name).replace('$price', price);
var $newRow = $(newRowHtml);
var $lastMenuRow = $row.closest('.menu-category').find('.menu-row').last();
$newRow.insertAfter($lastMenuRow);
});
Sorry for my poor explaining skills.
Clear the name and price after you get the values...
...
var name = $row.find('input').first().val();
var price = $row.find('input').last().val();
$row.find('input').first().val('');
$row.find('input').last().val('');
...

Calculating sum of order with changing price values in Javascript

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

How to pass a variable inside a jquery function $.each($("abc")...?

I'm trying to iterate a bunch of SELECT OPTION html drop-down fields and from the ones that are NOT empty, take the values and add a hidden field for a PAYPAL shopping cart.
My problem is that for some reason, the variable "curitem" is not passed inside the each function and I can't add the hidden field like they should. All I get is "NaN" or "undefined".
What PAYPAL expects is: item_name_1, item_name_2, etc. All numbers must iterate by +1.
How can I do this?
Thanks a bunch in advance
var curitem;
$.each($("select"), function(index, item) {
var attname = $(this).attr("name");
var nom = $(this).attr("data-nom");
var prix = $(this).attr("data-val");
var partname = attname.substring(0, 1);
var qte = $(this).val();
// i want all my <select option> items that the NAME start with "q" AND have a value selected
if (partname == "q" && isNaN(qte) == false && qte > 0) {
// item name
var inp2 = document.createElement("input");
inp2.setAttribute("type", "hidden");
inp2.setAttribute("id", "item_name_"+curitem);
inp2.setAttribute("name", "item_name_"+curitem);
inp2.setAttribute("value", nom);
// amount
var inp3 = document.createElement("input");
inp3.setAttribute("type", "hidden");
inp3.setAttribute("id", "amount_"+curitem);
inp3.setAttribute("name", "amount_"+curitem);
inp3.setAttribute("value", prix);
// qty
var inp4 = document.createElement("input");
inp4.setAttribute("type", "hidden");
inp4.setAttribute("id", "quantity_"+curitem);
inp4.setAttribute("name", "quantity_"+curitem);
inp4.setAttribute("value", qte);
// add hidden fields to form
document.getElementById('payPalForm').appendChild(inp2);
document.getElementById('payPalForm').appendChild(inp3);
document.getElementById('payPalForm').appendChild(inp4);
// item number
curitem = curitem + 1;
}
});
I think you have to initialize curitem variable.
var curitem = 1;

Categories

Resources