I'm new in JavaScript and JQuery
I have some input group of Items with 3 parameters which are Price, Discount, and Quantity.
I'd like to sum it up first before submitting it to see how much the total is.
so far here's what I got:
<input type="number" name="price[]" placeholder="price">
<input type="number" name="qty[]" placeholder="quantity">
<input type="number" name="dsc[]" placeholder="discount">
<input type="number" name="price[]" placeholder="price">
<input type="number" name="qty[]" placeholder="quantity">
<input type="number" name="dsc[]" placeholder="discount">
<input type="number" name="price[]" placeholder="price">
<input type="number" name="qty[]" placeholder="quantity">
<input type="number" name="dsc[]" placeholder="discount">
<button type="button" onClick="Total()"></button>
In my mind I could use a loop such as :
total = 0;
for(i = 0; i < count(price); i++){
total += price[i] * qty[i] * dsc[i] / 100;
}
also, what if I delete a group, will the array index changes?
Use jQuery.map to convert Objects to array of values
function Total() {
let total = 0;
//Convert to array of values
let price = $("input[name='price[]']").map((i, el) => $(el).val());
let qty = $("input[name='qty[]']").map((i, el) => $(el).val());
let dsc = $("input[name='dsc[]']").map((i, el) => $(el).val());
//I prefer each over for
$.each(price, (i, element) => {
total += price[i] * qty[i] * dsc[i] / 100;
//if 'dsc' is discount in % may be the formula is different:
//example : price = 100 quantity = 1;dsc = 20; => grossRowTotal = 100 * 1 = 100; total = 100 - (100*20/100) = 100 - 20 = 80;
//let grossRowTotal = price[i] * qty[i];
//total += grossRowTotal - (grossRowTotal * dsc[i]/ 100);
});
console.log(total);
$("#result").html(total);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" name="price[]" placeholder="price">
<input type="number" name="qty[]" placeholder="quantity">
<input type="number" name="dsc[]" placeholder="discount">
<input type="number" name="price[]" placeholder="price">
<input type="number" name="qty[]" placeholder="quantity">
<input type="number" name="dsc[]" placeholder="discount">
<input type="number" name="price[]" placeholder="price">
<input type="number" name="qty[]" placeholder="quantity">
<input type="number" name="dsc[]" placeholder="discount">
<button type="button" onClick="Total()">Total</button>
<div id="result"></div>
I don't know what exactly result you want.
this code may help you . try it and edit as per your requirement.
function Total()
{
let total=0;
for(i=0;i<$("input[id=price]").length;i++)
{
let p=$("input[id=price]")[i].value;
let q=$("input[id=qty]")[i].value;
let d=$("input[id=dsc]")[i].value;
total+=(p*q)-d;
}
$("#total").val(total);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" id="price" placeholder="price">
<input type="number" id="qty" placeholder="quantity">
<input type="number" id="dsc" placeholder="discount">
<br/>
<input type="number" id="price" placeholder="price">
<input type="number" id="qty" placeholder="quantity">
<input type="number" id="dsc" placeholder="discount">
<br/>
<input type="number" id="price" placeholder="price">
<input type="number" id="qty" placeholder="quantity">
<input type="number" id="dsc" placeholder="discount">
<br/>
<button type="button" onClick="Total()">Total</button>
<input type="number" id="total" placeholder="total">
Related
I have a collection of inputs
<input type="text" name="item" id="item" value="Name">
<input type="number" name="unit_price" id="unit_price" value="100">
<input type="number" name="qty" id="qty" value="2">
<input type="number" name="discount" id="discount" value="0">
<input type="text" name="item" id="item" value="Name 2">
<input type="number" name="unit_price" id="unit_price" value="200">
<input type="number" name="qty" id="qty" value="5">
<input type="number" name="discount" id="discount" value="10">
I'm trying to loop through all of these inputs to create an object with keys exactly the same as names in my inputs and add those values as values.
So my steps are:
let arr = []
inputs.forEach((elem) => {
console.log(elem.value)
arr.push({
'item': elem.value,
'unit_price': elem.value,
'qty': elem.value,
'discount': elem.value
});
})
EDITED
the expected output should look like this:
arr = [{
'item': 'Name',
'unit_price': '100',
'qty': '2',
'discount': '0',
},
{
'item': 'Name 2',
'unit_price': '200',
'qty': '5',
'discount': '10'
}
]
You can iterate over the input elements in chunks of 4.
let inputs = document.querySelectorAll('input');
let res = [];
let names = ['item', 'unit_price', 'qty', 'discount'];
for (let i = 0; i < inputs.length; i += names.length)
res.push(names.reduce((acc, curr, j) => (acc[curr] = inputs[i + j].value, acc), {}));
console.log(res);
<input type="text" name="item" id="item" value="Name">
<input type="number" name="unit_price" id="unit_price" value="100">
<input type="number" name="qty" id="qty" value="2">
<input type="number" name="discount" id="discount" value="0">
<input type="text" name="item" id="item" value="Name 2">
<input type="number" name="unit_price" id="unit_price" value="200">
<input type="number" name="qty" id="qty" value="5">
<input type="number" name="discount" id="discount" value="10">
Well, maybe you can wrap your inputs inside divs, and then find each block of values and map the values into two objects. Like:
<div id="first">
<input type="text" name="item" id="item" value="Name">
<input type="number" name="unit_price" id="unit_price" value="100">
<input type="number" name="qty" id="qty" value="2">
<input type="number" name="discount" id="discount" value="0">
</div>
<div id="second">
<input type="text" name="item" id="item" value="Name 2">
<input type="number" name="unit_price" id="unit_price" value="200">
<input type="number" name="qty" id="qty" value="5">
<input type="number" name="discount" id="discount" value="10">
</div>
And in JS
const first = {}
const second = {}
document.querySelectorAll('input').forEach( input => {
if (input.parentElement.id === 'first') {
first[input.name] = input.value;
} else {
second[input.name] = input.value;
}
});
console.log(first, second);
If you want two separate objects, you can add a class to the inputs to group them like so.
<input class="item1" type="text" name="item" id="item" value="Name">
<input class="item1" type="number" name="unit_price" id="unit_price" value="100">
<input class="item1" type="number" name="qty" id="qty" value="2">
<input class="item1" type="number" name="discount" id="discount" value="0">
<input class="item2" type="text" name="item" id="item2" value="Name 2">
<input class="item2" type="number" name="unit_price" id="unit_price2" value="200">
<input class="item2" type="number" name="qty" id="qty2" value="5">
<input class="item2" type="number" name="discount" id="discount2" value="10">
Then, for the javascript, because you are wanting to turn an array of items into a single object, this is a good candidate to use a reduce!
function aggrigateInputs(className) {
const elements = document.getElementsByClassName(className)
return elements.reduce((acc, elem) => {
acc[elem.name] = elem.value;
return acc;
}, {})
}
const item1 = aggrigateInputs('item1');
const item2 = aggrigateInputs('item2');
console.log(item1, item2);
I need to double the price but the function is not working. The total not display. Below is the code.
This is my form:
<label>Price</label>
<input type="text" id="price" name="price" value="<%=rs.getDouble(2)%>" onchange="autoprice()"/>
<label>Total</label>
<input type="text" id="total" name="total" readonly="readonly"/>
my script:
<script>
function autoprice(){
var x = document.getElementById("price").value;
document.getElementById("total").value = (x * 2).toFixed(2);
}
</script>
Here I made a snippet of your code and its working fine.
function autoprice() {
var x = document.getElementById("price").value;
document.getElementById("total").value = (x * 2).toFixed(2);
}
<label>Price</label>
<input type="text" id="price" name="price" value="" onchange="autoprice()" />
<label>Total</label>
<input type="text" id="total" name="total" readonly="readonly" />
Onchange needs the cursor move out of focus. After entering value press Tab or Enter. Use oninput, if you want to change it dynamically when the value is changed like the below code.
<label>Price</label>
<input type="text" id="price" name="price" value="" oninput="autoprice()"/>
<label>Total</label>
<input type="text" id="total" name="total" readonly="readonly"/>
<script>
function autoprice(){
var x = document.getElementById("price").value;
document.getElementById("total").value = (x * 2).toFixed(2);
}
</script>
I would like to take all values from all input fields and write them on the web.
Here is my code:
var button = document.querySelector("button");
button.addEventListener("click", function() {
var inputs = document.querySelectorAll("input").value;
for (i = 0; i < inputs.length; i++) {
inputs[i];
}
var output = document.getElementById("output");
output.innerHTML = "To sa: " + inputs;
});
<div>
<input type="number" min="1" max="49">
<input type="number" min="1" max="49">
<input type="number" min="1" max="49">
<input type="number" min="1" max="49">
<input type="number" min="1" max="49">
<input type="number" min="1" max="49">
</div>
<button>Check</button>
<div id="output"></div>
The expression document.querySelectorAll("input").value; does not give you the joined values of all selected inputs.
Instead, you could append the values to a new variable inside the for loop, through something like:
inputsAppended += inputs[i].value;
Finally, you can output it using:
output.innerHTML = "To sa: " + inputsAppended;
var button = document.querySelector("button");
button.addEventListener("click", function() {
var inputsAppended = "";
var inputs = document.querySelectorAll("input");
for (i = 0; i < inputs.length; i++) {
inputsAppended += inputs[i].value;
}
var output = document.getElementById("output");
output.innerHTML = "To sa: " + inputsAppended;
});
<div>
<input type="number" min="1" max="49">
<input type="number" min="1" max="49">
<input type="number" min="1" max="49">
<input type="number" min="1" max="49">
<input type="number" min="1" max="49">
<input type="number" min="1" max="49">
</div>
<button>Check</button>
<div id="output"></div>
var button = document.querySelector("button");
button.addEventListener("click", function() {
var inputs = document.querySelectorAll("input");
for (i = 0; i < inputs.length; i++) {
var output = document.getElementById("output");
output.innerHTML += inputs[i].value;
}
});
<div>
<input type="number" min="1" max="49">
<input type="number" min="1" max="49">
<input type="number" min="1" max="49">
<input type="number" min="1" max="49">
<input type="number" min="1" max="49">
<input type="number" min="1" max="49">
</div>
<button>Check</button>
<div id="output"></div>
Here is a simple approach where all numbers are printed in different lines
var button = document.querySelector("button");
button.addEventListener("click", function() {
//iterate all inputs, get their values, and join them separated by a line break
document.getElementById("output").innerHTML =
[].slice.call(document.querySelectorAll("input")).map( s => s.value ).join( "<br>" );
});
<div>
<input type="number" min="1" max="49">
<input type="number" min="1" max="49">
<input type="number" min="1" max="49">
<input type="number" min="1" max="49">
<input type="number" min="1" max="49">
<input type="number" min="1" max="49">
</div>
<button>Check</button>
<div id="output"></div>
Actually I want to add text fields by clicking on button. It is working but I am unable to remove the text fields by clicking on remove button. Please see the code below:
<script type="text/javascript">
var i = 1;
function more_fields() {
i++;
var objTo = document.getElementById('more_fields')
var divtest = document.createElement("div");
divtest.setAttribute("class", "form-group removeclass"+i);
var rdiv = 'removeclass'+i;
divtest.innerHTML = '<div><input type="text" name="comp[]" id="component"
value="" placeholder="Product" /> <input type="number"
name="quantity[]" id="quantity" placeholder="Quantity" /> <input
type="number" name="rate[]" id="rate" placeholder="Rate" /> <input
type="number" name="amount[]" id="amount" placeholder="Amount" readonly />
<button class="btn btn-danger" type="button" onclick="remove_more_fields('+
i +');" style="height:2em; width:3%;">X</button></div>';
objTo.appendChild(divtest)
}
function remove_more_fields(rid) {
$('.removeclass'+rid).remove();
}
</script>
<div class="form-group fieldgroup" id="more_fields">
<div>
<input type="text" name="comp[]" id="component" value=""
placeholder="Product" />
<input type="number" name="quantity[]"
id="quantity" placeholder="Quantity"/>
<input type="number" name="rate[]"
id="rate" placeholder="Rate" />
<input type="number" name="amount[]"
id="amount" placeholder="Amount" readonly/>
<button class="add_field_button"
type="button" onclick="more_fields()"> Add</button>
</div>
<br/>
</div>
How can I get that result? And I want to calculate the quantity*rate and display the result automatically in Amount field. If I change either quantity or rate, automatically amount will change and display the result. Please suggest me...Thank you.
Try this to get amount:
<div class="form-group fieldgroup" id="more_fields">
<div>
<input type="text" name="comp[]" id="component" value="" placeholder="Product" />
<input type="number" name="quantity[]" id="quantity" placeholder="Quantity" onchange="getAmount(this)" />
<input type="number" name="rate[]" id="rate" placeholder="Rate" onchange="getAmount(this)" />
<input type="number" name="amount[]" id="amount" placeholder="Amount" readonly/>
<button class="add_field_button" type="button" onclick="more_fields()"> Add</button>
</div>
<br/>
</div>
<script>
var i = 1;
function more_fields() {
i++;
var objTo = document.getElementById('more_fields');
var divtest = document.createElement("div");
divtest.setAttribute("class", "form-group removeclass" + i);
var rdiv = 'removeclass' + i;
divtest.innerHTML = '<div><input type="text" name="comp[]" id="component" value="" placeholder="Product" /> <input type="number" name="quantity[]" id="quantity" placeholder="Quantity" onchange="getAmount(this)" /> <input type="number" name="rate[]" id="rate" placeholder="Rate" onchange="getAmount(this)" /> <input type="number" name="amount[]" id="amount" placeholder="Amount" readonly /> <button class="btn btn-danger" type="button" onclick="remove_more_fields(' + i + ');" style="height:2em; width:3%;">X</button></div>';
objTo.appendChild(divtest)
}
function remove_more_fields(rid) {
$('.removeclass' + rid).remove();
}
function getAmount(el)
{
console.log(el.parentElement);
var inputs = el.parentElement.getElementsByTagName('input');
inputs[3].value = (parseInt(inputs[1].value) * parseFloat(inputs[2].value));
}
</script>
Here is working JSFiddle
Give the onclick function fro remove button like this - onclick="remove_more_fields(i);" . This would make the function call with value of i being passed to remove_more_fields function.
What I missed telling here is you can include the entire divtest.innerHTML definition in - <div>...</div> (note the quote here) , since my editor was showing error for the string spanning multiple lines. This might have triggered the evaluation of i and it worked perfectly fine for me.
I need to sum all prices and multiply them with quantity. Problem is that only first field calculates good, others take price value of first. Help please
This is were I came for now:
$('.orderForm__item').on('input', function() {
var totalSum = 0;
$('.quantity, .price').each(function() {
var quantity = $(this).val();
var price = $('.price').attr('value');
if ($.isNumeric(quantity)) {
totalSum += parseFloat(quantity) * parseFloat(price);
}
});
$('#total').text(totalSum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form" class="orderForm">
<div class="orderForm__item">
<label>Item</label>
<input min="0" max="99" type="number" class="quantity" name="quantity" /><br>
<span class="price" value="1.70">(1.70 KM)</span><br>
</div>
<div class="orderForm__item">
<label>Item</label>
<input min="0" max="99" type="number" class="quantity" name="quantity" /><br>
<span class="price" value="3">(3.0 KM)</span><br>
</div>
<div class="orderForm__item">
<label>Item</label>
<input min="0" max="99" type="number" class="quantity" name="quantity" /><br>
<span class="price" value="15">(15 KM)</span><br>
</div>
<div class="orderForm__item">
<label>Item</label>
<input min="0" max="99" type="number" class="quantity" name="quantity" /><br>
<span class="price" value="1.7">(1.70 KM)</span><br>
</div>
</form>
Total: <output id="total"></output>
You should each for orderForm__item and find quantity, price per item:
$('.orderForm__item').on('input', function() {
var totalSum = 0;
$('.orderForm__item').each(function() {
var quantity = $(this).find('.quantity').val();
var price = $(this).find('.price').attr('value');
if ($.isNumeric(quantity)) {
totalSum += parseFloat(quantity) * parseFloat(price);
}
});
$('#total').text(totalSum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form" class="orderForm">
<div class="orderForm__item">
<label>Item</label>
<input min="0" max="99" type="number" class="quantity" name="quantity" /><br>
<span class="price" value="1.70">(1.70 KM)</span><br>
</div>
<div class="orderForm__item">
<label>Item</label>
<input min="0" max="99" type="number" class="quantity" name="quantity" /><br>
<span class="price" value="3">(3.0 KM)</span><br>
</div>
<div class="orderForm__item">
<label>Item</label>
<input min="0" max="99" type="number" class="quantity" name="quantity" /><br>
<span class="price" value="15">(15 KM)</span><br>
</div>
<div class="orderForm__item">
<label>Item</label>
<input min="0" max="99" type="number" class="quantity" name="quantity" /><br>
<span class="price" value="1.7">(1.70 KM)</span><br>
</div>
</form>
Total: <output id="total"></output>