I have a list of persons that I need to display, and for each person there is an input for age.
I need to sum the ages when im writing; I mean if I have 5 persons when I'm on the 5th record, i need the total of previous 4 ages like this one : Calculate sum from number type input fields by javascript
this is my code :
<tr th:each="person : ${persons}">
<td th:text="${person.first_name}"></td>
<td th:text="${person.last_name}"></td>
<td th:text="${person.phone}"></td>
<td><input id="age" class="form-control"
type="text" name="age" th:field="*{ages}">
</td>
</tr>
Total : <input type="text" name="total" id="total"/>
I did this js script, but in total it gives me only the value of first line !!!! Any help ?
<script type="text/javascript">
$(document).ready(function(){
$("#age").each(function() {
$(this).on('input', function(){
calculateSum();
});
log.console("sum :"+sum);
});
});
function calculateSum() {
var sum = 0;
$("#age").each(function() {
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
$("#sum").html(sum.toFixed(2));
}
</script>
put all of the ages in array
On every place you want to show the sum of the previous ages:
2.1. slice the array from 0 to the place of the current value (beacuse slice(0,x) actually slicing the array from 0 to x-1).
2.2 execute the reduce function on the sliced array, you can see an example here: https://www.w3schools.com/jsref/jsref_reduce.asp
Related
I am trying to do a shopping cart where I want the total to automatically change after the quantity is inputted (the total is the price times the quantity). I'm trying to use Javascript for this and I just can't seem to get it as it is coming up with null and before it said NaN.
PS: It is a console log at the moment just to see if it works, but I will need it to go into the total input tag.
HTML:
<input id="price" type="text" readonly value="$18.95">
<input id="quantity" type="text" value="1" onchange="calcTotal()">
<input id="total" type="text" readonly value="$18.95">
JavaScript:
function calcTotal() {
var price = document.getElementById("price").value;
var quantity = document.getElementById("quantity").value;
var total = price * quantity;
console.log(total);
}
Try this:
function calcTotal() {
// remove $ sign and parse Float price
var price = parseFloat(document.getElementById("price").value.substr(1));
// parse float quantity
var quantity = parseFloat(document.getElementById("quantity").value);
var total = price * quantity;
//pass calculated value to input with id total
document.getElementById("total").value = "$" + total;
}
<input id="price" type="text" readonly value="$18.95">
<input id="quantity" type="text" value="1" onchange="calcTotal()">
<input id="total" type="text" readonly value="">
Any operation that involves a string returns NaN, however you should
coerce your input values as Number
function calcTotal() {
var price = document.getElementById("price").value;
var quantity = document.getElementById("quantity").value;
var total =Number(price) * Number(quantity);
console.log(total);
}
Using Number vs parseFloat
So as long as you have standard numeric input, there's no difference. However, if your input starts with a number and then contains other characters, parseFloat truncates the number out of the string, while Number gives NaN (not a number):
parseFloat('1x'); // => 1
Number('1x'); // => NaN
I have build a shopping cart where I want to update the price based on Quantity..But the problem I'm facing is using following javascript code that for the first item i could update the price based on Quantity but for the second item or next item i couldn't ..Can anyone help me out to find the Error please.
Here's my html :
<td class="total_price table-default total" >${{$row->price}}
<span></span></td>
<td class="qty table-default">
<input type="number" class="quantity" value="{{$row->no_of_items}}" name="qty" maxlength="3" max="999" min="1" /> ×${{$row->p_price}}
Here's the jQueryPart:
$(".quantity").change(update);
function update()
{
var qty = parseFloat($(this).val());
var net = parseFloat(document.getElementById("net_price").value);
var total = qty * net;
$('.total').html("$"+total);
}
Remove the following block:
$("#quantity").each(function(i){
so the function is:
function update(){
var qty = parseFloat($(this).val());
var net = parseFloat(document.getElementById("net_price").value);
var total = qty * net;
$('#total').html("$"+total);
}
I want to sum the product count which are added dynamically using JSON array.
<tr ng-repeat="(key,val) in form.products">
<td>{{ProductName(key)}}</td>
<td >
<input type="text" name="products" ng-model="form.products[key]" class="form-control">
</td>
</tr>
How can I get the sum of products in the above example?
use lodash
presuming the value you want to sum is in a property called 'price':
{{_(form.products).mapValues('price').sum()}}
you may need to get lodash into your scope first. In the controller, something like:
scope._ = _;
or this approach
you are using an 'object with properties' instead of 'an array of objects', that is why you cant use your example above , $scope.products.length;....
Your product object with its properties :
$scope.products ={
"1":"20",//property 1 with value 20
"2":"35",//property 2 with value 35
"3":"150"//property 3 with value 150
}
The data Object (object with properties as you have it):
$scope.myData = {"1":120,"2":250,"3":500};
Function that iterates into object's properties and sum the price:
//read object properties and sum price
$scope.calculateSum = function(data){
var sum=0;
var counter=0;
for (var property in data) {
if (data.hasOwnProperty(property)) {
sum += data[property];
counter++;
}
}
return sum;
};
Function that iterates into object properties and count the products
//read object properties and count the products
$scope.countProducts = function(data){
var counter=0;
for (var property in data) {
if (data.hasOwnProperty(property)) {
counter++;
}
}
return counter;
};
Into your HTML template:
<table>
<tr ng-repeat="(key,value) in myData track by $index">
<td>
<input type="text" name="id" ng-model="key" class="form-control">
</td>
<td>
<input type="text" name="price" ng-model="value" class="form-control">
</td>
</tr>
<tr>
<td>Products: {{countProducts(myData)}}</td>
<td>Sum: {{calculateSum(myData)}}</td>
</tr>
</table>
I have done a live example that counts the products and also sum the products price: http://plnkr.co/edit/FmJhvV?p=preview
Hope helps, good luck.
I'm having a problem in calling the values I entered in the numberbox (I don't know what should I call it... if there's a textbox, there should be a numberbox. lol). If I enter "123456", the value of sum should be "21", but what happens is that the value of sum is "0123456".
<input type="number" name="user" id="input" maxlength="6" size="6" required>
<input type="button" onClick="Calculate()" value="Calculate">
<script type="text/javascript">
function Calculate(){
var user = [];
user=document.getElementById("input").value;
if(user.length==6){
var sum=0;
for (i=0;i<user.length;i++){
sum=sum+user[i];
}
var ave=sum/6;
window.alert("Sum is: "+sum);
window.alert("Average is: "+ave);
}
else
window.alert("Please input EXACTLY 6 numbers.");
}
</script>
You are retrieving a string breaking it into parts and adding it back together.You need to convert the string into an integer first. To find out the multiple ways to do this, a very good answer on that is written here:
How do I convert a string into an integer in JavaScript?
sum = sum + parseInt(user[i],10);
Should work
How do I get the javascript and php to display two decimal places after calculation. Right now it works fine but no decimal places, just whole numbers
php********
<td> width="3"><input type="text" name="order_quan" /></td>
<td><input type="text" name="Price" /></td>
<td><font color="yellow"><span class=Price></span></td>
Java Script********
<script>
$('input[name=order_quan], input[name=Price]').keyup(function() {
var divParent = $(this).closest('div');
var order_quan = $('input[name=order_quan]', divParent).val()-0;
var Price = $('input[name=Price]', divParent).val()-0;
if (order_quan >= 0 && Price >= 0)
$('span.Price', divParent).text(order_quan*Price);
});
</script>
You can use .toFixed(2);
(order_quan * Price).toFixed(2);
Here's the basics
String((order_quan*Price * 100)>>0).replace(/(\d{2}$)/,'.$1');
//shift it 2 decimal places left, floor it, and add '.' before the last two digits