vuejs form Calcuations in LAravel Array - javascript

I have an issue I know might be basic but has been giving me a headache. Any help is highly appreciated
I have a form named timesheets looping through a dates array in laravel. I am trying to add up form fields hour + hour1 + hour2 and I want them added up and displayed in the total_hours field.
My problem is only the top row gets added(i don't get any errors in the web console)
!https://imgur.com/gNdJVNE
//app.js code
el: '#timesheet',
data: function(){
return {
hour: '',
hour1: '',
hour2: '',
hour3: '',
hour4: '',
hour5: '',
total_hours: ''
};
},
computed: {
TotalTimesheets: function() {
return (this.hour + this.hour1 + this.hour2 + this.hour3 + this.hour4 + this.hour5)
}
}
//my _form.blade.php code:
#foreach($dates as $date)
<strong>{{$date->date}}</strong>
<input type="text" name="hour[]" value="0" id="hour" v-model.number="hour" class="form-control">
#if(empty($analysis->act1))
#else
<input type="text" name="hour1[]" value="0" id="hour1" v-model.number="hour1" class="form-control>
#endif
#if(empty($analysis->act2))
#else
<input type="text" name="hour2[]" value="0" id="hour2" v-model.number="hour2" class="form-contro">
#endif
#if(empty($analysis->act3))
#else
<input type="text" name="hour3[]" value="0" id="hour3" v-model.number="hour3" class="form-control">
#endif
#if(empty($analysis->act4))
#else
<input type="text" name="hour4[]" value="0" id="hour4" v-model.number="hour4" class="form-control">
#endif
#if(empty($analysis->act5))
#else
<input type="text" name="hour5[]" value="0" id="hour5" v-model.number="hour5" class="form-control">
#endif
<input type="text" name="total_hours[]" :value="TotalTimesheets" id="total_hours" class="form-control" max="9" >
#endforeach
<div class="form-group">
<button type="submit" class="btn btn-primary btn-lg">{{ $buttonText }}</button>
</div>

I will give you only a guide. This is just a "pseudo code" I did not check it.
Firstly, you need to create a component to render only one row of your sheet. Something like:
<template>
<div>
<strong>{{date}}</strong>
<div v-for="(hour, index) in hours" :key="index" >
<input type="text" v-model.number="hour.value">
</div>
<input type="text" :value="total">
</div>
</template>
<script>
export default{
name: 'ActiveHoursRow'
props:['date','hours'],
computed:{
total(){
return this.hours.reduce((a, v) => a + v);
}
}
}
</script>
Secondly, you need to create a component that renders the whole sheet with the help of row-rendering component.
<template>
<div v-for="(row, index) in backendData">
<ActiveHoursRow :date="row.date" :hours="row.hours" />
</div>
</template>
<script>
export default{
name: 'ActiveHoursRow'
data: function(){
return {
"backendData":[
#foreach($dates as $date)
{
"date":"{{$date->date}}",
"hours": [
#if(empty($analysis->act1))
#else
{"name":"12_07_2019_act1", "value": 0},
#endif
#if(empty($analysis->act2))
#else
{"name":"12_07_2019_act2", "value": 0},
#endif
]
},
#endforeach
]
}
}
}
</script>
It also always better to draw data as JSON in and then use it. It is more clear to understand and later you can easily to switch to dynamic loading.
See more about components: https://v2.vuejs.org/v2/guide/components.html

thanks for the help, but I decided to use Jquery as shown below.
$(document).on("keyup change paste", "td > input.auto-calc", function() {
row = $(this).closest("tr");
h = parseFloat(row.find("td input.hour").val()) || 0;
h1 = parseFloat(row.find("td input.hour1").val()) || 0;
h2 = parseFloat(row.find("td input.hour2").val()) || 0;
h3 = parseFloat(row.find("td input.hour3").val()) || 0;
h4 = parseFloat(row.find("td input.hour4").val()) || 0;
h5 = parseFloat(row.find("td input.hour5").val()) || 0;
row.find(".total_hours").val(h + h1 + h2 + h3 + h4 + h5);
var sum = 0;
var sum1 = 0;
var sum2 = 0;
var sum3 = 0;
var sum4 = 0;
var sum5 = 0;
var sum6 = 0;
$("input.total_hours").each(function() {
sum += +$(this).val();
});
$("input.hour").each(function() {
sum1 += +$(this).val();
});
$("input.hour1").each(function() {
sum2 += +$(this).val();
});
$("input.hour2").each(function() {
sum3 += +$(this).val();
});
$("input.hour3").each(function() {
sum4 += +$(this).val();
});
$("input.hour4").each(function() {
sum5 += +$(this).val();
});
$("input.hour5").each(function() {
sum5 += +$(this).val();
});
$("#total-month").text(sum);
$("#total-hour").text(sum1);
$("#total-hour1").text(sum2);
$("#total-hour2").text(sum3);
$("#total-hour3").text(sum4);
$("#total-hour4").text(sum5);
$("#total-hour5").text(sum6);
});
var i = 0;
$('.addy').on('click', function () {
++i;
addy();
});
function addy(){
var tr='<tr>'
+'<td><input type="text" name="timesheets['+i+'][date]" id="date[]" class="form-control " data-provide="datepicker" autocomplete="off"><input type="hidden" id="analysis_id" name="timesheets['+i+'][analysis_id]" value="{{$analysis->analysisid}}">'
+'<input type="hidden" id="activity_id5" name="timesheets['+i+'][activity_id5]" value="{{#$tact6->activity_id5}}"><input type="hidden" id="activity_id4" name="timesheets['+i+'][activity_id4]" value="{{#$tact5->activity_id4}}"><input type="hidden" id="activity_id3" name="timesheets['+i+'][activity_id3]" value="{{#$tact4->activity_id3}}"><input type="hidden" id="activity_id2" name="timesheets['+i+'][activity_id2]" value="{{#$tact3->activity_id2}}"><input type="hidden" id="activity_id1" name="timesheets['+i+'][activity_id1]" value="{{#$tact2->activity_id1}}"><input type="hidden" id="activity_id" name="timesheets['+i+'][activity_id]" value="{{#$tact1->activity_id}}"></td>'
+'<td><input type="text" name="timesheets['+i+'][hour]" value="0" id="hour" class="form-control hour auto-calc"></div></td>'
+'#if(empty($analysis->act1)) #else <td><input type="number" name="timesheets['+i+'][hour1]" value="0" id="hour1" class="form-control hour1 auto-calc" min="0" max="8"></div></td>#endif'
+'#if(empty($analysis->act2)) #else <td><input type="number" name="timesheets['+i+'][hour2]" value="0" id="hour2" class="form-control hour2 auto-calc" min="0" max="8"></div></td>#endif'
+'#if(empty($analysis->act3)) #else <td><input type="number" name="timesheets['+i+'][hour3]" value="0" id="hour3" class="form-control hour3 auto-calc" min="0" max="8"></div></td>#endif'
+'#if(empty($analysis->act4)) #else <td><input type="number" name="timesheets['+i+'][hour4]" value="0" id="hour4" class="form-control hour4 auto-calc" min="0" max="8"></div></td>#endif'
+'#if(empty($analysis->act5)) #else <td><input type="number" name="timesheets['+i+'][hour5]" value="0" id="hour5" class="form-control hour5 auto-calc" min="0" max="8"></div></td>#endif'
+'<td><div class="input-group mb-3"><div class="input-group-prepend"><span class="input-group-text"><i class="fa fa-list-ol"></i></span></div><input type="text" name="timesheets['+i+'][total_hours]" id="total_hours" class="form-control total_hours" max="9" ></div><input type="hidden" id="approved" name="timesheets['+i+'][approved]" value="No"> <input type="hidden" id="approved_by" name="timesheets['+i+'][approved_by]" value="{{$approved->supervisor_id}}"></td>'
+'<td><button type="button" class="btn btn-danger remove">Remove</button></td>'
+'</tr>'
$('tbody').append(tr);
};
$('body').on('click','.remove', function () {
var last=$('tbody tr').length;
$(this).parent().parent().remove();
});

Related

How to dynamically select elements with document.querySelectorAll() for function call?

I have been working on this fiddle:
https://jsfiddle.net/j1vrb7to/165/
The code in that fiddle is this:
HTML:
<div id="CalculationContainer">
<input type="numbers" class="form-control new-tuition" /> <br />
<input type="numbers" class="form-control new-tuition" /> <br />
<input type="numbers" class="form-control new-tuition" /><br /><br />
<input type="numbers" id="new-tuition-total" disabled="disabled" /><br /> <br />
<input type="numbers" class="form-control new-state" /> <br />
<input type="numbers" class="form-control new-state" /> <br />
<input type="numbers" class="form-control new-state" /><br /><br />
<input type="numbers" id="new-state-total" disabled="disabled" />
</div>
JavaScript:
const NewTuitionInputs = document.querySelectorAll("div#CalculationContainer > input.new-tuition");
const NewStateInputs = document.querySelectorAll("div#CalculationContainer > input.new-state");
NewTuitionInputs.forEach(function(input) {
input.onchange = function() {
var total = 0;
NewTuitionInputs.forEach(function(input) {
total += parseInt(input.value);
});
document.getElementById("new-tuition-total").value = total;
}
});
NewStateInputs.forEach(function(input) {
input.onchange = function() {
var total = 0;
NewStateInputs.forEach(function(input) {
total += parseInt(input.value);
});
document.getElementById("new-state-total").value = total;
}
});
As the users enter values into the textboxes, I want to update the value of another field to display running totals. Ultimately I will need to keep track of 20+ running totals on my form. Instead of maintaining 20+ functions, is it possible to use a single function to calculate running totals on the fly? Here is some pseudocode to demonstrate what I'm thinking:
var ThisInput = document.querySelectorAll("div#CalculationContainer > input.[INPUT_CLASS_PARAMETER_HERE]");
ThisInput.forEach(function(input) {
input.onchange = function() {
var total = 0;
ThisInput.forEach(function(input) {
total += parseInt(input.value);
});
document.getElementById("[DYNAMICALLY_CHOOSE_WHERE_TO_DISPLAY").value = total;
}
});
You have a convention that the inputs have a class and then the total has an id with that class name plus -total. You can use this to your advantage in making a general purpose function:
function trackTotals(className){
var inputs = document.querySelectorAll(`div#CalculationContainer > input.${className}`);
inputs.forEach(input => {
input.addEventListener("change",()=>{
var total = [...inputs].reduce((acc,i) => acc + (parseInt(i.value,10) || 0),0);
document.getElementById(`${className}-total`).value = total;
})
})
}
Usage would then be:
trackTotals("new-tuition");
trackTotals("new-state");
// whatever else that follows same conventions
Live example follows:
trackTotals("new-tuition");
trackTotals("new-state");
function trackTotals(className){
var inputs = document.querySelectorAll(`div#CalculationContainer > input.${className}`);
inputs.forEach(input => {
input.addEventListener("change",()=>{
var total = [...inputs].reduce((acc,i) => acc + (parseInt(i.value,10) || 0),0);
document.getElementById(`${className}-total`).value = total;
})
})
}
<div id="CalculationContainer">
<input type="numbers" class="form-control new-tuition"/> <br/>
<input type="numbers" class="form-control new-tuition"/> <br/>
<input type="numbers" class="form-control new-tuition"/><br/><br/>
<input type="numbers" id="new-tuition-total" disabled="disabled"/><br /><br />
<input type="numbers" class="form-control new-state"/> <br/>
<input type="numbers" class="form-control new-state"/> <br/>
<input type="numbers" class="form-control new-state"/><br/><br/>
<input type="numbers" id="new-state-total" disabled="disabled"/>
</div>
Yes, you can create a function that takes the id:
function doTotal(name) {
var ThisInput = document.querySelectorAll(`div#CalculationContainer > input.${name}`);
ThisInput.forEach(function(input) {
input.onchange = function() {
var total = 0;
ThisInput.forEach(function(input) {
total += parseInt(input.value);
});
document.getElementById(`${name}-total`).value = total;
}
});
}
Note that I'm using string templates to build the selector strings.
You can use the event delegation method:
const calcContainer = document.getElementById('CalculationContainer')
, sumElms =
{ tuition: { sum: document.getElementById('new-tuition-total'), elms: [...document.querySelectorAll('input.new-tuition')] }
, state: { sum: document.getElementById('new-state-total'), elms: [...document.querySelectorAll('input.new-state')] }
}
;
calcContainer.oninput= ({target}) =>
{
if (!target.matches('.new-tuition, .new-state')) return
let sumElm = target.matches('.new-tuition') ? sumElms.tuition : sumElms.state
sumElm.sum.value = sumElm.elms.reduce((s,e)=>s+e.valueAsNumber,0)
}
#CalculationContainer input {
float: left;
clear:both;
width: 5em;
}
#CalculationContainer input:disabled {
margin-bottom: 1em;
font-weight: bold;
color:black;
}
<div id="CalculationContainer">
<input type="number" class="form-control new-tuition" value="0">
<input type="number" class="form-control new-tuition" value="0">
<input type="number" class="form-control new-tuition" value="0">
<input type="number" id="new-tuition-total" disabled="disabled" value="0">
<input type="number" class="form-control new-state" value="0">
<input type="number" class="form-control new-state"value="0">
<input type="number" class="form-control new-state"value="0">
<input type="number" id="new-state-total" disabled="disabled"value="0">
</div>

calculation of packing charges in java script

I have an tax invoice page for making invoice. I am using javascript for calculating the amount. I want to add courier charges in javascript. Can anybody help me?
Here is code
function calculateTotal() {
var totalAmount = 0;
$("[id^='price_']").each(function() {
var id = $(this).attr('id');
id = id.replace("price_", '');
var price = $('#price_' + id).val();
var quantity = $('#quantity_' + id).val();
if (!quantity) {
quantity = 1;
}
var total = price * quantity;
$('#total_' + id).val(parseFloat(total));
totalAmount += total;
});
$('#subTotal').val(parseFloat(totalAmount));
var taxRate = $("#taxRate").val();
var subTotal = $('#subTotal').val();
if (subTotal) {
var taxAmount = subTotal * taxRate / 100;
$('#taxAmount').val(taxAmount);
subTotal = parseFloat(subTotal) + parseFloat(taxAmount);
$('#totalAftertax').val(subTotal);
var amountPaid = $('#amountPaid').val();
var totalAftertax = $('#totalAftertax').val();
if (amountPaid && totalAftertax) {
totalAftertax = totalAftertax - amountPaid;
$('#amountDue').val(totalAftertax);
} else {
$('#amountDue').val(subTotal);
}
}
CSS is only for demo ( you can ignore it )
I added packaging fees & shipping fees with also FREE option each
$(document).ready(function() {
calculateTotal();
});
function calculateTotal() {
var totalAmount = 0;
$("[id^='price_']").each(function() {
var id = $(this).attr('id').replace("price_", '');
var price = $('#price_' + id).val();
var quantity = $('#quantity_' + id).val();
if (!quantity) {
quantity = 1;
}
var total = price * quantity;
$('#total_' + id).val(parseFloat(total));
totalAmount += total;
});
$('#subTotal').val(parseFloat(totalAmount));
var taxRate = parseFloat($("#taxRate").val());
var subTotal = parseFloat($('#subTotal').val());
if (subTotal) {
var taxAmount = subTotal * taxRate / 100;
$('#taxAmount').val(taxAmount);
subTotal = parseFloat(subTotal) + parseFloat(taxAmount);
$('#totalAftertax').val(subTotal);
var amountPaid = $('#amountPaid').val();
var totalAftertax = $('#totalAftertax').val();
if (amountPaid && totalAftertax) {
totalAftertax = totalAftertax - amountPaid;
$('#amountDue').val(totalAftertax);
} else {
$('#amountDue').val(subTotal);
}
var amoutDue = parseFloat($('#amountDue').val());
var shipping = parseFloat($('#shipping').val());
var packaging = parseFloat($('#packaging').val());
$('#amountDue').val(amoutDue + shipping + packaging);
}
}
[disabled],
[readonly] {
background-color: #eee;
border: 1px solid #ccc;
color: #888;
}
div {
padding: 5px 10px;
}
div:nth-child(even) {
background: #eee;
}
label {
display: inline-block;
width: 120px;
}
<div>
<input id="price_1" type="number" value="5" />
<input id="quantity_1" type="number" value="3" min="1" />
<input id="total_1" type="number" value="15" readonly />
</div>
<div>
<input id="price_3" type="number" value="15" />
<input id="quantity_3" type="number" value="1" min="1" />
<input id="total_3" type="number" value="15" readonly />
</div>
<div>
<input id="price_8" type="number" value="20" />
<input id="quantity_8" type="number" value="2" min="1" />
<input id="total_8" type="number" value="40" readonly />
</div>
<div align="center">
<button type="button" onclick="calculateTotal()">Update Cart</button>
</div>
<hr />
<div><label>Sub Total:</label>
<input id="subTotal" type="number" value="0" readonly /></div>
<div><label>Tax Rate:</label>
<input id="taxRate" type="number" value="15" readonly /></div>
<div><label>Tax Amount:</label>
<input id="taxAmount" type="number" value="0" readonly /></div>
<div><label>Total After Tax:</label>
<input id="totalAftertax" type="number" value="0" readonly /></div>
<div>
<label>Shipping:</label>
<select id="shipping" onchange="calculateTotal()">
<option value="0">Regular FREE ( 12-15 days )</option>
<option value="12.99">Express $12.99 ( 1-2 days )</option>
<option value="9.99">UPS $9.99 ( 2-3 days )</option>
<option value="6.99">DHL $6.99 ( 3-5 days )</option>
</select>
</div>
<div>
<label>Packaging:</label>
<select id="packaging" onchange="calculateTotal()">
<option value="0">Regular FREE</option>
<option value="2.99">Package 1 $2.99</option>
<option value="4.99">Package 2 $4.99</option>
<option value="7.99">Package 3 $7.99</option>
</select>
</div>
<div><label>Amount Paid:</label> <input id="amountPaid" type="number" value="15" readonly /></div>
<div><label>Amount Due:</label> <input id="amountDue" type="number" value="0" readonly /></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

How to multiple (a*b) two input text value and show it Dynamicly with text change in javascript?

i want to show the money that customer must pay and my inputs are like this :
<input type="text" class="form-control" placeholder="cost " id="txt" name="credit">
<input type="text" class="form-control" placeholder="quantity" id="txt" name="limit">
when the input text is changing i want to show the total cost (quantity*cost) in a <p> tag Dynamicly how can it be with javascript?
You can try this:
<input type="text" class="form-control" placeholder="cost " id="credit" name="credit" onchange="calculate()">
<input type="text" class="form-control" placeholder="quantity" id="limit" name="limit" onchange="calculate()">
<p id="result"></p>
And javascript part:
function calculate() {
var cost = Number(document.getElementById("credit"));
var limit = Number(document.getElementById("limit"));
document.getElementById("result").innerHTML= cost*limit;
}
You must ensure you entered numbers in inputs.
All of the above will generate errors if both the boxes are blank . Try this code , its tested and running .
<script>
function calc()
{
var credit = document.getElementById("credit").value;
var limit = document.getElementById("limit").value;
if(credit == '' && limit != '')
{
document.getElementById("cost").innerHTML = parseInt(limit);
}
else if(limit == '' && credit != '')
{
document.getElementById("cost").innerHTML = parseInt(credit);
}
else if(limit!= '' && credit!= '')
{
document.getElementById("cost").innerHTML = parseInt(limit) * parseInt(credit);
}
else
{
document.getElementById("cost").innerHTML = '';
}
}
</script>
</head>
<input type="number" value="0" min="0" class="form-control" placeholder="cost" id="credit" name="credit" onkeyup="calc();">
<input type="number" value="0" min="0" class="form-control" placeholder="quantity" id="limit" name="limit" onkeyup="calc();">
<p id="cost"></p>
Hope this will be useful
// get cost field
var _cost = document.getElementById("cost");
_cost.addEventListener('keyup',function(event){
updateCost()
})
// get quantity field
var _quantity = document.getElementById("quantity");
_quantity.addEventListener('keyup',function(event){
updateCost()
})
function updateCost(){
var _getCost = document.getElementById("cost").value;
var _getQuantity = document.getElementById("quantity").value;
var _total = _getCost*_getQuantity;
console.log(_total);
document.getElementById("updateValue").textContent = ""; // Erase previous value
document.getElementById("updateValue").textContent = _total // update with new value
}
jsfiddle
In case you consider using JQuery I've made this fiddle.
See if it works for you.
https://fiddle.jshell.net/9cpbdegt/
$(document).ready(function() {
$('#credit').keyup(function() {
recalc();
});
$('#limit').keyup(function() {
recalc();
});
function recalc() {
var credit = $("#credit").val();
var limit = $("#limit").val();
var result = credit * limit;
$("#result").text(result);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control" placeholder="cost " id="credit" name="credit" value="0">x
<input type="text" class="form-control" placeholder="quantity" id="limit" name="limit" value="0">
<p id="result">0</p>
Try this:
<script >
function myFunction() {
document.getElementById('totalcost').innerHTML = document.getElementById('txt').value * document.getElementById('txt2').value;}
</script>
Also, change your HTML to this:
<input type="text" onkeypress="myFunction()" onkeyup="myFunction()" onclick="myFunction()" onmousemove="myFunction()" class="form-control" placeholder="cost " id="txt" name="credit">
<input type="text" onkeypress="myFunction()" onkeyup="myFunction()" onclick="myFunction()" onmousemove="myFunction()" class="form-control" placeholder="quantity" id="txt2" name="limit">
Enter cost and quantity.
Note the change with the second input: id='txt' was changed to id='txt2'. This is because no 2 elements can have the same id.
Note: Untested.

jquery sum of multiple input fields if same class in one input

Hello I need to sum the values of same class input in one input with class name total.
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="total" value="" />
Possible?
A working fiddle here
$(document).on("change", "qty1", function() {
var sum = 0;
$("input[class *= 'qty1']").each(function(){
sum += +$(this).val();
});
$(".total").val(sum);
});
You pretty much had it, just needed to adjust your JQuery a little bit for the appropriate selectors
updated fiddle : http://jsfiddle.net/5gsBV/7/
$(document).on("change", ".qty1", function() {
var sum = 0;
$(".qty1").each(function(){
sum += +$(this).val();
});
$(".total").val(sum);
});
I suggest this solution:
html
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="qty1" value="" />
<input type="text" class="total" value="" />
<div id="result"></div>
js
$(".qty1").on("blur", function(){
var sum=0;
$(".qty1").each(function(){
if($(this).val() !== "")
sum += parseInt($(this).val(), 10);
});
$("#result").html(sum);
});
fiddle
I think your issue is here:
$("#destination").val(sum);
change it to:
$(".total").val(sum);
And instead of change event i suggest you to use keyup instead.
$(document).on("keyup"
$(document).on("keyup", ".qty1", function() {
var sum = 0;
$(".qty1").each(function(){
sum += +$(this).val();
});
$(".total").val(sum);
});
We can use following own function
(function( $ ){
$.fn.sum=function () {
var sum=0;
$(this).each(function(index, element){
sum += parseFloat($(element).val());
});
return sum;
};
})( jQuery );
//Call $('.abcd').sum();
http://www.gleegrid.com/code-snippet/javascript/jquery-sum-input-values-by-class/?filter=bygroup&group=JQuery
$('.qty1').each(function(){
sum += parseFloat(this.value);
});
console.log(sum);
This will work with pure js
<input type="text" value=" " class="percent-input"> <br>
<input type="text" value=" " class="percent-input"> <br>
<input type="text" value=" " class="percent-input"> <br>
<p>Total Value :<span id="total">100%</span></p>
<p>Left Value :<span id="left">0.00%</span></p>
var percenInput = document.querySelectorAll('.percent-input');
for (let i = 0; i < percenInput.length; i++) {
percenInput[i].addEventListener('keyup', getPercentVal)
}
function getPercentVal() {
var total = 0;
var allPercentVal = document.querySelectorAll('.percent-input');
for (var i = 0; i < allPercentVal.length; i++) {
if (allPercentVal[i].value > 0) {
var ele = allPercentVal[i];
total += parseFloat(ele.value);
}
}
document.getElementById("total").innerHTML = total.toFixed(2) + '%';
document.getElementById("left").innerHTML = (100 - total).toFixed(2) + '%';
}
You almost had it:
$(document).on("change", ".qty1", function() {
var sum = 0;
$(".qty1").each(function(){
sum += +$(this).val();
});
$(".total").val(sum);
});
http://jsfiddle.net/DUKL6/1
The problem with all of the above answers is that they fail if you enter something other than a number. If you want something that is more friendly to users, you should do some validation, perhaps even give some feedback when a value other than a number is entered.
$('body').on('change', '.qty1', function() {
var total=0;
$(".qty1").each(function(){
quantity = parseInt($(this).val());
if (!isNaN(quantity)) {
total += quantity;
}
});
$('.total').val('Total: '+total);
});
<input type="text" class="price" placeholder="enter number one" />
<input type="text" class="price" placeholder="enter number two" />
<input type="text" class="price" placeholder="enter number three" />
<input type="text" class="price" placeholder="enter number four" />
<input type="text" id="total">
<script>
$(document).ready( function() {
$(document).on("keyup", ".price", function() {
var sum = 0;
$(".price").each(function(){
sum += +$(this).val();
});
$('#total').val(sum);
});
});
</script>

Calculate Sum of Multiple Input Numbers JQuery

I have 3 inputs and I'm trying to get the sum of the numbers each time a user updates one of them.
HTML
<input class="my-input" type="number" name="" value="0" min="0">
<input class="my-input" type="number" name="" value="0" min="0">
<input class="my-input" type="number" name="" value="0" min="0">
JS
var sum = 0;
$('.my-input').each(function(index, elem){
var value = $(this).val();
sum += parseFloat($(elem).val());
console.log(sum);
$(this).on('keyup click', function (){
sum += parseFloat($(elem).val());
});
});
But I keep getting crazy results..
EDIT:
I tried this:
function getSum(){
var sum = 0;
$('.my-input').each(function(index, elem){
var value = $(this).val();
sum += parseFloat($(elem).val());
});
return sum;
}
$('.my-input').each(function(){
$(this).on('keyup click', function(){
console.log( this.value );
var curSum = getSum();
console.log('current sum: ' + curSum);
});
});
Consider this example:
<input class="my-input" type="number" name="" value="0" min="0" />
<input class="my-input" type="number" name="" value="0" min="0" />
<input class="my-input" type="number" name="" value="0" min="0" />
<input type="text" id="total" value="" />
<script type="text/javascript">
// just get keyup event
$('.my-input').on('keyup', function(){
var total = 0;
// on every keyup, loop all the elements and add all the results
$('.my-input').each(function(index, element) {
var val = parseFloat($(element).val());
if( !isNaN( val )){
total += val;
}
});
$('#total').val(total);
});
</script>

Categories

Resources