Adding and subtracting using dynamic variable names in JQuery/Javascript - javascript

I am working on developing an inventory checking form for my restaurant. The idea is that I can weigh for example a partially full bottle of Vodka (for example!) and from that weight the volume in milliliters will be automatically calculated based on the weight (adjuster) and density of the product.
The code is automatically generated with PHP. Here is an example, I choose which bottle of vodka and based on that choice I would like to display the amount in the span '1_liveWeight'. The problem I am having due to my limited experience is with this line of code:
var qty = (weight - adjuster) * density;
I would like it to function like this:
var qty = (weight - adjuster_!value selected from item_1!) * density!value selected from item_1!
The bits between the ! being where I would like to insert the value.
Below is an extract of the code generated in php.
HTML
<select id='item_1'>
<option value='3'>Smirnoff Vodka 1000ml</option>
<option value='4'>Absolute Vodka 750ml</option>
</select>
<input type='hidden' id='adjuster_3' value='140'>
<input type='hidden' id='density_3' value='0.96'>
<input type='hidden' id='adjuster_4' value='100'>
<input type='hidden' id='density_4' value='0.96'>
<input type='text' id ='weight_1' name ='weight'>
<span id='1_liveWeight'>0</span>
JQuery
$(document).ready(function(){
$("#item_1").change(function(){
var item = $('#item_1').val();
var adjuster3 = $('#adjuster_3').val();
var density3 = $('#density_3').val();
var adjuster4 = $('#adjuster_4').val();
var density4 = $('#density_4').val();
var weight = $('#weight_1').val();
var qty = (weight - adjuster)*density+item;
$("#1_liveWeight").html("<b>"+ qty +"</b>");
});
});
I hope I've explained my issue well enough! Thanks for the help,
DB

You need to assign the correct adjuster and density variable based on the item selection:
$(document).ready(function(){
$("#item_1").change(function(){
var item = $('#item_1').val();
var adjuster3 = $('#adjuster_3').val();
var density3 = $('#density_3').val();
var adjuster4 = $('#adjuster_4').val();
var density4 = $('#density_4').val();
var weight = $('#weight_1').val();
weight = Number(weight);
var adjuster, density;
if(item == 3){
adjuster = Number(adjuster3);
density = Number(density3);
}
else if(item == 4){
adjuster = Number(adjuster4);
density = Number(density4);
}
var qty = (weight - adjuster) * density;
$("#1_liveWeight").html("<b>"+ qty +"</b>");
});
});

I'd probably do it something more like this:
$(document).ready(function(){
var density = 0;
var adjuster = 0;
$("#item_1").change(function(){
recalculateWgt();
});
$("#weight_1").keyup(function(){
recalculateWgt();
});
recalculateWgt();
function recalculateWgt() {
var item = $('#item_1').val();
var adjuster = $('#adjuster_' + item).val();
var density = $('#density_' + item).val();
var weight = $('#weight_1').val();
var qty = (weight - adjuster)*density+item;
$("#1_liveWeight").html("<b>"+ qty +"</b>");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='item_1'>
<option value='3'>Smirnoff Vodka 1000ml</option>
<option value='4'>Absolute Vodka 750ml</option>
</select>
<input type='hidden' id='adjuster_3' value='140'>
<input type='hidden' id='density_3' value='0.96'>
<input type='hidden' id='adjuster_4' value='100'>
<input type='hidden' id='density_4' value='0.96'>
<input type='text' id ='weight_1' name ='weight'>
<span id='1_liveWeight'>0</span>
You could use $("#weight_1").change() if you preferred to have the value update only when the quantity field loses focus.

I would say vodka really helped me a lot to understand but still i couldn't figure out - do you need details for just the selected product or for all when your dropdown changes? .Anyway here is something
$(document).ready(function(){
$("#item_1").change(function(){
var item = $('#item_1').val(); // may be 3 or 4 or whatever depends on choice
var adjuster = $('#adjuster_'+ item).val(); // dynamic selector
var density = $('#density_'+item).val();
var weight = $('#weight_'+item).val();
var qty = (weight - adjuster)*density; // density is constant at a given temp. for given liquid why were you chaging this? dilluting?
$("#"+item+"_liveWeight").html("<b>"+ qty +"</b>");
});
});

I ended up solving the problem by learning about eval()
It worked as intended:
eval("var chosenAdjuster = adjuster"+item);
eval("var chosenDensity = density"+item);
var qty = (weight - chosenAdjuster) * chosenDensity;

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>

Calculate data to an input field from 2 select fields with 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;

Calculating prices by javascript in laravel

I'm using laravel and I want to sum two numbers and show it in my blade.
Logic
I have hidden input field which is holding my product price
I have drop-down options which users can select
When users select any of the options my product price should sum to
that option price and return the result as total to users.
Codes
<!--hidden field of product price-->
<input type="hidden" id="harga" name="harga" value="{{$product->price}}">
<!--div to show total price-->
<div id="totalPriceInTotal"></div>
<!--my options-->
<select name="attr[]" class="form-control">
<option value="">{{ __('Select') }}</option>
#foreach($optioncollection as $suboption)
<option value="{{$suboption->id}}">{{$suboption->title}} - {{ __('Rp') }} {{ number_format($suboption->price, 0) }}</option>
#endforeach
</select>
JavaScript:
<script>
$(document).ready(function() {
var optionprice = document.getElementById('harga').val();
$.ajax({
success:function(data) {
// var optionprice = $(#attr).val();
var shipingcost = parseFloat(data)+parseFloat(optionprice);
var shipingcostnumber = shipingcost;
var nf = new Intl.NumberFormat('en-US', {
maximumFractionDigits:0,
minimumFractionDigits:0
});
$('#totalPriceInTotal').append('<p>Cost: Rp '+nf.format(shipingcostnumber)+'</p>');
}
});
});
</script>
PS: I am aware that my JavaScript code is wrong, what I'd tried to do
here was to getting my hidden input value in my totalPriceInTotal
div which obviously was unsuccessful and then try to add my drop-down
values into it.
Questions
What should I change to get my hidden input value in my
totalPriceInTotal div when page loads?
How do I add my options value into it?
Note: for my options part i cannot add my options prices into value="" part because i need that value to be id for my cart so I added the price in options like {{ number_format($suboption->price, 0) }} probably i need help to remove texts around this price before i can actually sum it with my product price.
thanks in advance.
I advise giving the hidden field a data attribute, e.G
<input type="hidden" id="harga" name="harga" data-price="{{$product->price}}">
Then in JavaScript you can do this:
$('#harga').data('price');
You can do the same for the dropdown, although I do not fully comprehend what this does
{{$suboption->id}}">{{$suboption->title}} - {{ __('Rp') }} {{ number_format($suboption->price, 0) }}
You can then take both values and add them to each other, and then append them to the "totalPriceInTotal" div (which is a terrible name imho ^^)
If appending does not work, just use
$('#totalPriceInTotal').val() = '<p>Cost: Rp ' + calculatedPrice + '</p>';
At this point I am not sure what EXACTLY does not work for you, so if you need more help, please let me know!
SOLVED
So Ihad to add function in my controller in order to get my drop-down options prices and here is my final code I commented my parts for better understanding
<script>
$(document).ready(function() {
// if option is not selected shows product price
$('#totalPriceInTotal').empty();
var productprice = $('#harga').val();
var shipingcost = parseFloat(productprice);
var shipingcostnumber = shipingcost;
var nf = new Intl.NumberFormat('en-US', {
maximumFractionDigits:0,
minimumFractionDigits:0
});
$('#totalPriceInTotal').append('Rp '+nf.format(shipingcostnumber)+'');
// if option is selected will sum product price and option price
$('select[name="attr[]"]').on('change', function() {
var productprice = $('#harga').val();
var optionprice = $(this).val();
if(optionprice) {
$.ajax({
url: '{{ url('admin/getoptionprice') }}/'+encodeURI(optionprice),
type: "GET",
dataType: "json",
success:function(data) {
$('#totalPriceInTotal').empty();
var shipingcost = parseFloat(data)+parseFloat(productprice);
var shipingcostnumber = shipingcost;
var nf = new Intl.NumberFormat('en-US', {
maximumFractionDigits:0,
minimumFractionDigits:0
});
$('#totalPriceInTotal').append('Rp '+nf.format(shipingcostnumber)+'');
}
});
}else{
// if user decided to back to default and not using any option price will back to normal
$('#totalPriceInTotal').empty();
var productprice = $('#harga').val();
var shipingcost = parseFloat(productprice);
var shipingcostnumber = shipingcost;
var nf = new Intl.NumberFormat('en-US', {
maximumFractionDigits:0,
minimumFractionDigits:0
});
$('#totalPriceInTotal').append('Rp '+nf.format(shipingcostnumber)+'');
}
});
});
</script>
Hope this can help others.

How to use data value to refer back to another variable

I'm trying to use create a converter by using the data attribute to refer back to a previous value.
I cannot seem to get:
data-my_currency to refer back to 301.46
data-this to refer back to 4259.00
$('input').keyup(function() {
var BTC = 4259.00
var ETH = 301.46
var LTC = 67.72
var USD = 1
var EUR = 0.83
var CNY = 6.46
var convertFrom = $('.js').data('my_currency');
//Should refer back to EUR var
var convertTO = $('.js').data('this');
//Should refer back to BTC var
var amount = $('input').val();
var result = convertFrom * convertTO * amount;
var newresult = result.toFixed(2);
$('.output').html(newresult);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="js" data-my_currency="EUR"></div>
<div class="js" data-this="BTC"></div>
<input type="text" class="input" />
<div class="output">Me</div>
Alternatively and without changing your existing code much, you can declare your variables at global scope (which you should avoid) and use window object to get the value of the variable.
var BTC = 4259.00
var ETH = 301.46
var LTC = 67.72
var USD = 1
var EUR = 0.83
var CNY = 6.46
$(document).ready(function () {
$('input').keyup(function () {
var convertFrom = $('[data-my_currency]').data('my_currency');
var convertTO = $('[data-this]').data('this');
var amount = $('input').val(); //Assuming user enters only numbers
var result = window[convertFrom] * window[convertTO] * amount;
var newresult = result.toFixed(2);
$('.output').html(newresult);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="js" data-my_currency="EUR"></div>
<div class="js" data-this="BTC"></div>
<input type="text" class="input" />
<div class="output">Me</div>
If you are attempting to make them refer back to the JavaScript variables, why not simply use those JavaScript variables directly?
If, however, you have your Bitcoin and currency prices written as an element in the page (which is what I assume is the case), you're looking for $('.js[data-my_currency]')[0].innerHTML and $('.js[data-this]')[0].innerHTML respectively.
Breaking this down:
.js targets the class js
[data-my_currency] targets the attribute data-my_currency
$('.js[data-my_currency]') returns a nodeList
[0] grabs the first node
.innerHTML grabs the content inside of that node.
$('input').keyup(function() {
var convertFrom = $('.js[data-my_currency]')[0].innerHTML;
var convertTO = $('.js[data-this]')[0].innerHTML;
var amount = $('input').val();
var result = convertFrom * convertTO * amount;
var newresult = result.toFixed(2);
$('.output').html(newresult);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="js" data-my_currency="EUR">0.83</div>
<div class="js" data-this="BTC">4259.00</div>
<input type="text" class="input" />
<div class="output">Me</div>
Hope this helps! :)

How make automatic calculate

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.

Categories

Resources