Calculate the values of input where each input has different prices. Any shorter code for this?(javascript only) - javascript

The code below is working fine but what if there are 100 inputs? any shorter way to do this?
function checkTotal() {
var a = document.getElementById("sandwich").value;
var b = document.getElementById("burger").value;
var c = document.getElementById("cake").value;
var d = document.getElementById("coffee").value;
document.getElementById("total").value = parseInt(a) * 10 + parseInt(b) * 5 + parseInt(c) * 15 + parseInt(d) * 20;
}
<form role="form" name="listForm">
<label>Sandwich</label>
<input type="number" id="sandwich" value="0" onkeyup="checkTotal()"><br>
<label>Burger</label>
<input type="number" id="burger" value="0" onkeyup="checkTotal()"><br>
<label>Cake</label>
<input type="number" id="cake" value="0" onkeyup="checkTotal()"><br>
<label>Coffee</label>
<input type="number" id="coffee" value="0" onkeyup="checkTotal()"><br> Total: <input type="text" size="2" name="total" id="total" value="0" />
</form>
1) Here each input article has a different price.
2) The value of the input should be mutiply with its price given(Eg. if the sandwich has a price:30, and user inputs value 2 it should calculte the total=price*input value.)
3) i have my code which is working fine but is the above code is the right way to do?
4) what if there are 100 of article inputs. is there shorter code or should i create variable for each one?

what if there are 100 of article inputs. is there shorter code or
should i create variable for each one?
You can maintain a map
var idPriceMap = {
"sandwich" : 20,
"burger" : 10,
"cake" : 5,
"coffee" : 10
};
You can iterate this and produce your value using reduce
var output = Object.keys( idPriceMap ).reduce( function(a,b){
var value = +document.getElementById( b ).value;
a += value * idPriceMap[ b ];
return a;
}, 0);
document.getElementById( "total" ).value = output;

Another way to try is to give your elements a class and some data attributes that can be retrieved by JavaScript using dataset. You can then use them to make your calculations. That way you get rid of ids and you just have to change the HTML code to add a new element.
function checkTotal() {
var total = 0,
foods = document.querySelectorAll('.food');
for (var i = 0; i < foods.length; i++) {
var food = foods[i],
name = food.dataset.item,
price = parseInt(food.dataset.price),
howMany = parseInt(food.value);
console.log(howMany, name, 'costs', (howMany * price));
total += howMany * price;
}
document.getElementById('total').value = total;
}
<form role="form" name="listForm">
<label>Sandwich</label>
<input class="food" data-item="sandwich" data-price="30" type="number" value="0" onBlur="checkTotal()"><br>
<label>Burger</label>
<input class="food" data-item="burger" data-price="10" type="number" value="0" onBlur="checkTotal()"><br>
<label>Cake</label>
<input class="food" data-item="cake" data-price="5" type="number" value="0" onBlur="checkTotal()"><br>
<label>Coffee</label>
<input class="food" data-item="coffee" data-price="15" type="number" value="0" onBlur="checkTotal()"><br>
Total: <input type="text" size="2" name="total" id="total" value="0" />
</form>
As a side note, you should give a try on Angular or Knockout which can help you to achieve those operations.

Related

Changing unit price for different quantities

I have this price calculator where the price for each item is 2. I need the price to be 1.8 if the quantity is over 1000. In another condition it also could be treated as discount, for example if the quantity is bigger than 1000, then discount 10%
I've tried using an if condition, but I couldn't figure out how to solve this.
function calculate(price) {
var qty = document.getElementById("qty").value || 0;
qty = parseFloat(qty).toFixed(2);
var result = parseFloat(qty * 2).toFixed(2);
document.getElementById("result").value = result;
if (result >= 1000) {
result = result - 10%
}
}
<form role="form" id="price" name="price">
<p>
<input type="text" id="qty" onchange="calculate(qty*2)" value="">
</p>
<p>
<input type="text" id="result" value="" disabled>
</p>
</form>
The issue is because 10% isn't a valid term. You need to work out the percentage mathematically and remove it from the total, something like this:
const itemPrice = 2;
const result = document.querySelector('#result');
document.querySelector('#qty').addEventListener('input', e => {
const qty = parseInt(e.target.value, 10);
const subtotal = itemPrice * qty;
const discount = qty > 1000 ? 0.1 : 0; // 0.1 here = 10%
const total = subtotal - subtotal * discount;
result.value = total.toFixed(2);
});
<form role="form" id="price" name="price">
<p>
<input type="text" id="qty" value="" />
</p>
<p>
<input type="text" id="result" value="" disabled />
</p>
</form>
Note that this logic is intentionally verbose simply for demonstrative purposes. You can make it more succinct if necessary.

Use array values as constant

how can I use array values as constant like ; aaa 500,bbb 350,ccc 25 and at last calc value 1725.
const vals = ["aaa", "bbb", "ccc"];
clength = vals.length;
i=0;
while (i < clength)
{
vals[i] = document.getElementById(vals[i]).value;
i=i+1
};
document.getElementById("calc").value = (aaa + bbb)*2 + ccc;
<input id="aaa" value="500">
<input id="bbb" value="350">
<input id="ccc" value="25">
<br>
<br>
<br>
<input id="calc">
how can I use array values as constant like ;
aaa 500,bbb 350,ccc 25 and at last calc value 1725.
I want while loop behave like ;
aaa = 500; bbb= 350; ccc = 25;
NOTE : Please think array function as endless.(aaa,bbb,ccc is just samples)
There's many ways to do it but without changing your code much you could use a desctructive assignment:
const [aaa, bbb, ccc] = vals;
document.getElementById("calc").value = (aaa + bbb)*2 + ccc;
It would be better to use a key/value pairs though:
document.getElementById('calc').value = calc(resolveCalcValues());
function calc(vals) {
return (vals.aaa + vals.bbb) * 2 + vals.ccc;
}
function resolveCalcValues() {
return valuesOf('aaa', 'bbb', 'ccc');
}
function valuesOf(...inputIds) {
return inputIds.reduce((vals, id) => {
vals[id] = document.getElementById(id).value;
return vals;
}, {});
}
<input id="aaa" type="number" value="500">
<input id="bbb" type="number" value="350">
<input id="ccc" type="number" value="25">
<input id="calc">
You can dynamically create variables through the window object and remember to convert strings to number to calculate with them:
const vals = ["aaa", "bbb", "ccc"];
for (const val of vals) {
window[val] = +document.getElementById(val).value;
}
document.getElementById("calc").value = (aaa + bbb)*2 + ccc;
<input id="aaa" value="500">
<input id="bbb" value="350">
<input id="ccc" value="25">
<br>
<br>
<br>
<input id="calc">
Following is a more generic approach based on adding different class names to the inputs server side and doesn't involve using any ID or variables at all
function collectionSum (selector){
const els = Array.from(document.querySelectorAll(selector))
return els.reduce((a,c) => a + Number(c.value),0);
}
const combined = collectionSum('.values.combine'),
add = collectionSum('.values.add');
document.getElementById("calc").value = combined * 2 + add;
<input class="values combine" id="aaa" value="500">
<input class="values combine" id="bbb" value="350">
<input class="values add" id="ccc" value="25">
<br>
<br>
<br>
<input id="calc">

Did not get total from second input fields?

I am new to javascript writing some code by myself using DOM technique. My First block of code work properly and it gives me sum to first two input fields but i didn't get sum when i entered values of 2nd block of code. here is my code
<body>
<script language ="javascript">
function Calculate(){
var pricee = document.getElementById('price').value;
var qtyy = document.getElementById('qty').value;
var sum = pricee * qtyy;
document.getElementById('total').value = sum;
var newprice = document.getElementById('price2').value;
var newqty = document.getElementById('qty2').value;
var sum2 = newprice * newqty;
document.getElementById('total2').value = sum2;
}
</script>
<form>
Product Name: <input type="text" id="name" name="productName">
<br>
Product Price: <input type="text" id="price" name="productPrice">
<br>
Product Qty: <input type="text" id="qty" name="productQty" type="text" id="total" name="producttotal"
onChange="Calculate()">
<br>
Total: <input type="text" id="total" name="producttotal">
<hr>
Product Name: <input type="text" id="name2" name="productName">
<br>
Product Price: <input type="text" id="price2" name="productPrice">
<br>
Product Qty: <input type="text" id="qty2" name="productQty" type="text" id="total" name="producttotal"
onChange="Calculate()">
<br>
Total: <input type="text" id="total2" name="producttotal">
</form>
There are two main issues with your code:
Your input types are text, so their value is treated as text. You should rather convert those values to numbers instead before doing mathematicals operations on them.
Your "Qty" inputs have multiple id and name and type. It's probably a copy-paste error.
To fix point 1, you can add a cast to number using the unary operator (+) like this:
function Calculate(){
var pricee = +document.getElementById('price').value;
var qtyy = +document.getElementById('qty').value;
var sum = pricee * qtyy;
document.getElementById('total').value = sum;
var newprice = +document.getElementById('price2').value;
var newqty = +document.getElementById('qty2').value;
var sum2 = newprice * newqty;
document.getElementById('total2').value = sum2;
}
To fix point 2, you just need to remove extra tags from your inputs:
First one:
Product Qty: <input type="text" id="qty" name="productQty" type="text" id="total" name="producttotal"
onChange="Calculate()">
should become this:
Product Qty: <input type="text" id="qty" name="productQty" onChange="Calculate()">
And second one should follow the same rule.
Also, you should add the onChange event on every input concerning the calculation.
Full working code:
HTML:
Product Name: <input type="text" id="name" name="productName">
<br>
Product Price: <input type="text" id="price" onChange="Calculate()" name="productPrice">
<br>
Product Qty: <input type="text" id="qty" name="productQty" onChange="Calculate()">
<br>
Total: <input type="text" id="total" name="producttotal">
<hr>
Product Name: <input type="text" id="name2" name="productName">
<br>
Product Price: <input type="text" id="price2" onChange="Calculate()" name="productPrice">
<br>
Product Qty: <input type="text" id="qty2" onChange="Calculate()" name="productQty"
onChange="Calculate()">
<br>
Total: <input type="text" id="total2" name="producttotal">
Javascript:
function Calculate(){
var pricee = +document.getElementById('price').value;
var qtyy = +document.getElementById('qty').value;
var sum = pricee * qtyy;
document.getElementById('total').value = sum;
var newprice = +document.getElementById('price2').value;
var newqty = +document.getElementById('qty2').value;
var sum2 = newprice * newqty;
document.getElementById('total2').value = sum2;
}
Working fiddle to play with: https://jsfiddle.net/cjxs7pLo/1/
As a side (irrelevant) note, you're defining a variable called sum whose value is the product of two values. This is not relevant in any way for the code, but its name is misleading and should be fixed, since other people reading your code may think it's a sum, but it's not a sum.

How to calculate two input fields and have the total display within an Input Element

I'm trying to multiply two input fields and have the result display within the total input element. Can someone tell me where is my problem within this code:
var amount = document.getElementById("amount").value;
var amount = parseInt(amount, 10);
var quantity = document.getElementById("quantity").value;
var quantity = parseInt(quantity, 10);
var total = amount * quantity;
document.getElementById("total").innerHTML = total;
Amount: <input type="number" id="amount" name="amount">
<br> Quantity: <input type="number" id="quantity" name="quantity">
<br> Total: <input type="number" id="total" name="total">
Use document.getElementById("total").value instead of document.getElementById("total").innerHTML = total. Also, you need to trigger your code on a particular event. Here I have just set it up to trigger when the user enters a value into either input field using the oninput="calc()" attribute on both your input fields:
function calc() {
var amount = document.getElementById("amount").value;
var amount = parseInt(amount, 10);
var quantity = document.getElementById("quantity").value;
var quantity = parseInt(quantity, 10);
var total = amount * quantity;
document.getElementById("total").value = total;
}
Amount: <input type="number" id="amount" name="amount" oninput="calc();">
<br> Quantity: <input type="number" id="quantity" name="quantity" oninput="calc();">
<br> Total: <input type="number" id="total" name="total">
Probably you need to bind an event either to a button (click) or to the input elements (input)
In this example, a button triggers the calculation.
Here the following adjustments:
Use the attribute .value for input-form elements.
Use the object Number or plus + sign to convert to a number.
Validates the entered values (this is up to you).
document.getElementById('calculate').addEventListener('click', function() {
var amount = document.getElementById("amount").value;
var amount = +amount;
var quantity = document.getElementById("quantity").value;
var quantity = +quantity;
var total = amount * quantity;
document.getElementById("total").value = total;
});
Amount: <input type="number" id="amount" name="amount">
<br> Quantity: <input type="number" id="quantity" name="quantity">
<br>
<br> <input id='calculate' type='button' value='Calculate'>
<br>
<br> Total: <input type="number" id="total" name="total">
you should add a function, and call it on input change
so try to use oninput event
and change document.getElementById("total").innerHTML = total; to be document.getElementById("total").value = total;
<html><head></head><body>
Amount: <input type="number" oninput="calculate()" id="amount" name="amount">
<br>
Quantity: <input type="number" oninput="calculate()" id="quantity" name="quantity">
<br>
Total: <input type="number" id="total" name="total">
<script>
function calculate(){
var amount = document.getElementById("amount").value;
var amount = parseInt(amount, 10);
var quantity = document.getElementById("quantity").value;
var quantity = parseInt(quantity, 10);
var total = amount * quantity;
document.getElementById("total").value = total;
}
</script>
</body>
</html>
function compute() {
var p = document.getElementById("principal").value;
var r = document.getElementById("rate").value;
var t = document.getElementById("time").value;
var answer = (p * r * t) / 100;
document.getElementById("answer").value = answer;
}

Get value from element id instead of name in javascript

I have some line of javascript which is works well if it gets value from the same series of names. But I have a problem later when each values passed to another page which I'd like to break down which value is belongs to. So the question is how can I change the way the script calculate the value from 'name' to 'id'. As the codes below:
<script type="text/javascript">
//auto commas
function doThousands(n) {
n = '' + n;
if (n.length < 4) return n;
var c = n.length % 3;
var pre = n.substring(0, c);
return pre + (pre.length? ',' : '') + n.substring(c).match(/\d{3}/g).join(',');
}
//sub total
function checkTotal() {
document.cc_form.total.value = '';
var sum = <?=$days*$_rate*$_rooms?>;
for (i=0;i<document.cc_form.cost.length;i++) {
if (document.cc_form.cost[i].checked) {
sum = sum + parseInt(document.cc_form.cost[i].value);
}
}document.cc_form.total.value = doThousands(sum);
}
</script>
And this is the HTML:
<form name="cc_form" id="cc_form" method="post" action="/">
<label for="transfer1"><input type="checkbox" id="transfer1" name="cost" value="800" autocomplete="off" onchange="checkTotal()" /> Taxi (800 THB | 2 pax)</label><br />
<label for="transfer2"><input type="checkbox" id="transfer2" name="cost" value="1200" autocomplete="off" onchange="checkTotal()" /> Mini Van (1,200 THB | 6 pax)</label><br />
<label for="xbed"><input type="checkbox" id="xbed" name="cost" value="1200" autocomplete="off" onchange="checkTotal()" /> Extra Bed (1,200 THB)</label><br />
<input type="text" id="total" name="total" />
</form>
document.getElementById http://www.w3schools.com/jsref/met_doc_getelementbyid.asp

Categories