If I had a list of inputs that were dynamically created, who's ID was appended to each input's name, what would be the best way of getting the value of each line item and then calculating a line by line total, as well as a grand total?
HTML:
<table>
<tr>
<td>
<input type="text" name="CompetencyList[0].Score">
<input type="text" name="SkillsList[0].Score">
<input type="text" name="LineTotal">
</td>
</tr>
<tr>
<td>
<input type="text" name="CompetencyList[1].Score">
<input type="text" name="SkillsList[1].Score">
<input type="text" name="LineTotal">
</td>
</tr>
<tr>
<td>
<input type="text" name="CompetencyList[2].Score">
<input type="text" name="SkillsList[2].Score">
<input type="text" name="LineTotal">
</td>
</tr>
<tr>
<td>
Grand Total: <input type="text" name="grandTotal"/>
</td>
</tr>
To calculate each line
$('[name="LineTotal"]').val(function() {
return $(this).closest('td').find('input').not(this).map(function() {
return +this.value || 0;
}).get().reduce(function(a, b) { return a + b });
});
once that's done, you'd calculate the total
$('[name="grandTotal"]').val(function() {
return $('[name="LineTotal"]').map(function() {
return +this.value;
}).get().reduce(function(a, b) { return a + b });
});
$('input').on('input', calculate);
function calculate() {
$('[name="LineTotal"]').val(function() {
return $(this).closest('td').find('input').not(this).map(function() {
return +this.value || 0;
}).get().reduce(function(a, b) { return a + b });
});
$('[name="grandTotal"]').val(function() {
return $('[name="LineTotal"]').map(function() {
return +this.value;
}).get().reduce(function(a, b) { return a + b });
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<input type="text" name="CompetencyList[0].Score">
<input type="text" name="SkillsList[0].Score">
<input type="text" name="LineTotal">
</td>
</tr>
<tr>
<td>
<input type="text" name="CompetencyList[1].Score">
<input type="text" name="SkillsList[1].Score">
<input type="text" name="LineTotal">
</td>
</tr>
<tr>
<td>
<input type="text" name="CompetencyList[2].Score">
<input type="text" name="SkillsList[2].Score">
<input type="text" name="LineTotal">
</td>
</tr>
<tr>
<td>
Grand Total:
<input type="text" name="grandTotal" />
</td>
</tr>
</table>
When you create your inputs dynamically, you can add to every input a class. Then you can use jQuery to get list of items that has this class. For example:
<input type="text" class="myInput" name="CompetencyList[0].Score">
<input type="text" class="myInput" name="SkillsList[0].Score">
<input type="text" class="myInput" name="LineTotal">
And in Javascript
var myImputs = $(".myInput");
Here's a JS fiddle to how I'd do it... https://jsfiddle.net/cz6sgbyc/1/
I have added classes of lineTotal, competencyScore, and skillsScore to the associated inputs, and an id of "grandTotal" to the grand total input.
Javascript:
function updateScores() {
var grandTotal = 0;
$('.lineTotal').each( function( index, input ) {
var $parent = $(input).parent();
var thisScore = parseFloat( $('.competencyScore',$parent).val() || 0 ) + parseFloat( $('.skillsScore',$parent).val() || 0 );
grandTotal += thisScore;
$(input).val( thisScore );
});
$('#grandTotal').val( grandTotal );
}
$(function() {
$('input').change( updateScores );
});
HTML:
<table>
<tr>
<td>
<input type="text" class="competencyScore" name="CompetencyList[0].Score">
<input type="text" class="skillsScore" name="SkillsList[0].Score">
<input type="text" class="lineTotal" name="LineTotal">
</td>
<td>
<input type="text" class="competencyScore" name="CompetencyList[1].Score">
<input type="text" class="skillsScore" name="SkillsList[1].Score">
<input type="text" class="lineTotal" name="LineTotal">
</td>
<td>
<input type="text" class="competencyScore" name="CompetencyList[2].Score">
<input type="text" class="skillsScore" name="SkillsList[2].Score">
<input type="text" class="lineTotal" name="LineTotal">
</td>
<td>
Grand Total: <input type="text" id="grandTotal" name="grandTotal"/>
</td>
</tr>
</table>
Related
I have the following dynamic table
I want to compare the value of submit Quantity textbox and Stock textbox together to check if Submit Quantity value is greater than stock value for all rows.
When submit Quantity textbox loses focus I want check, if Submit Quantity value is greater than stock, I want show an alert that "Not enough goods exist in stock" and Submit Quantity textbox must receive focus again.
My HTML and C#
<tbody>
#{ var i = 0;}
#foreach (var item in Model)
{
<tr>
<td></td>
<td>
<input type="text" name="[#i].GoodsName" readonly="readonly" asp-for="#item.GoodsName" class="form-control" />
</td>
<td>
<input type="text" name="[#i].BrandName" readonly="readonly" asp-for="#item.BrandName" class="form-control" />
</td>
<td>
<input type="text" name="[#i].Quantity" readonly="readonly" asp-for="#item.Quantity" class="form-control" />
</td>
<td>
<input type="number" onblur="compare()" id="submitQ" class="form-control" />
</td>
<td>
<input type="text" name="stock" id="stock" readonly="readonly" class="form-control" />
</td>
</tr>
}
I have no idea how to do that
Any help will be appreciated
Thanks in advance
Edit:
This is what I have done to achieve the result but it only works on first row Submit Quantity textbox not on second row
function compare() {
$('#submitQ').each(function () {
let submit = $('#submitQ').val();
let quantity = $('#stock').val();
if (submit > quantity) {
alert('Not enough goods!')
$('#submitQ').select();
return false
}
})
You cannot have mutliple elements with same ids instead use class selector .Then , just get value of submit quantity using $(this).val() and stock value using .closest('tr').find('.stock').. then simply compare these values .
Demo Code :
$('.submitQ').on("blur", function() {
//get value of submit qnty
let submit = $(this).val();
//get stock
let quantity = parseInt($(this).closest('tr').find('.stock').val());
if (submit > quantity) {
alert('Not enough goods!')
$(this).focus(); //show focus
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<th>No</th>
<th>Name</th>
<th>Brand</th>
<th>Requested Quantity</th>
<th>Submit Quantity</th>
<th>Stock</th>
</thead>
<tbody>
<tr>
<td>1</td>
<td>
<input type="text" name="[#i].GoodsName" readonly="readonly" asp-for="#item.GoodsName" value="something" class="form-control" />
</td>
<td>
<input type="text" name="[#i].BrandName" readonly="readonly" asp-for="#item.BrandName" class="form-control" />
</td>
<td>
<input type="text" name="[#i].Quantity" readonly="readonly" asp-for="#item.Quantity" class="form-control" />
</td>
<td>
<!--use class-->
<input type="number" class="submitQ" class="form-control" />
</td>
<td>
<input type="text" name="stock" value="8" class="stock" readonly="readonly" class="form-control" />
</td>
</tr>
<tr>
<td>2</td>
<td>
<input type="text" name="[#i].GoodsName" readonly="readonly" asp-for="#item.GoodsName" value="something" class="form-control" />
</td>
<td>
<input type="text" name="[#i].BrandName" readonly="readonly" asp-for="#item.BrandName" class="form-control" />
</td>
<td>
<input type="text" name="[#i].Quantity" readonly="readonly" asp-for="#item.Quantity" class="form-control" />
</td>
<td>
<input type="number" class="submitQ" class="form-control" />
</td>
<td>
<input type="text" name="stock" value="5" class="stock" readonly="readonly" class="form-control" />
</td>
</tr>
</tbody>
</table>
Please check my fiddle.
Fiddle
When i enter any data in any rows in slab_range, i need to autofill all the other rows of 'Slab Range' with a value 'No Bid'. If i left blank, nothing has to be filled. Likewise if i enter any data in 'Part Number', all the other rows of 'Part Number' has to be filled with value '2'. The rows are coming from db, so i cant tell how many rows it will be, it should iterate all the rows.
<tr>
<td>
<input size="1" id="sl[0]" name="sl[0]" value="1" type="text">
</td>
<td>
<input size="9" data-validation="required" name="slab_range[]" id="slab_range[]" type="text">
</td>
<td>
<input size="9" name="item_partno[]" id="item_partno[]" type="text">
</td>
</tr>
There you go, now it's your task to refactoring the code because both methods are equals.
var ProcessTable = (function () {
var _slabs, _partsNumber;
var _init = function () {
_slabs = $('input[name^="slab_range"]');
_partsNumber = $('input[name^="item_partno"]');
_slabs.on('blur', _slabBlurHandler);
_partsNumber.on('blur', _partNumberBlurHandler);
};
var _slabBlurHandler = function (e) {
var value = $.trim($(this).val());
if (value !== '') {
_slabs.val('No bid');
} else {
_slabs.val('');
}
$(this).val(value); // Because the previous line override the original value
};
var _partNumberBlurHandler = function (e) {
var value = $.trim($(this).val());
if (value !== '') {
_partsNumber.val('2');
} else {
_partsNumber.val('');
}
$(this).val(value); // Because the previous line override the original value
};
return {
init: _init
}
})();
ProcessTable.init();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="cart1" name="cart" method="post" class="single" action="price_edit_save.php?supplier_name=Jupiter+Microwave+Components+Inc&tender_id=151501">
<div class="clone_row">
<table style="border-collapse: collapse;" id="table" border="1" cellpadding="2" cellspacing="2" width="100%">
<thead>
<tr bgcolor="#E6E6FA">
<th width="4%">SlNo</th>
<th width="4%">Slab Range</th>
<th width="6%">Part Number</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input size="1" name="id[0]" value="9978" readonly="readonly" type="hidden">
<input size="1" id="sl[0]" name="sl[0]" value="1" type="text">
<input size="1" id="item_id[0]" name="item_id[0]" readonly="readonly" type="hidden">
</td>
<td>
<input size="9" data-validation="required" name="slab_range[]" id="slab_range[]" type="text">
</td>
<td>
<input size="9" name="item_partno[]" id="item_partno[]" type="text">
</td>
</tr>
<tr>
<td>
<input size="1" name="id[1]" value="9979" readonly="readonly" type="hidden">
<input size="1" id="sl[1]" name="sl[1]" value="2" type="text">
<input size="1" id="item_id[1]" name="item_id[1]" readonly="readonly" type="hidden">
</td>
<td>
<input size="9" data-validation="required" name="slab_range[]" id="slab_range[]" type="text">
</td>
<td>
<input size="9" name="item_partno[]" id="item_partno[]" type="text">
</td>
</tr>
<tr>
<td>
<input size="1" name="id[1]" value="9979" readonly="readonly" type="hidden">
<input size="1" id="sl[1]" name="sl[1]" value="2" type="text">
<input size="1" id="item_id[1]" name="item_id[1]" readonly="readonly" type="hidden">
</td>
<td>
<input size="9" data-validation="required" name="slab_range[]" id="slab_range[]" type="text">
</td>
<td>
<input size="9" name="item_partno[]" id="item_partno[]" type="text">
</td>
</tr>
</tbody>
</table>
</div>
<div class="addMoreDIV">
</div>
<table>
<tr>
<td>
<input value="--Update Data--" type="submit">
</td>
</tr>
</table>
</form>
And please, be more kindly when you ask for "help".
I have a table and with in tds i had a text box
<table class="table ratemanagement customtabl-bordered " id="rate_table">
<tbody>
<tr>
<th><input type="checkbox" onclick="select_all()" class="check_all"></th>
<th>From Days*</th>
<th>To Days*</th>
<th>Rent*</th>
</tr>
<tr>
<td>
<input class="case" type="checkbox">
</td>
<td class="v">
<input id="rate_fromdays" class="form-control" name="fromdays" type="text">
</td>
<td>
<input id="rate_todays" class="form-control" name="todays" type="text">
</td>
<td>
<input id="rate_rent" class="form-control" name="rent" type="text">
</td>
</tr>
<tr>
<td>
<input class="case" type="checkbox">
</td>
<td class="v">
<input id="rate_fromdays" class="form-control" name="fromdays" type="text">
</td>
<td>
<input id="rate_todays" class="form-control" name="todays" type="text">
</td>
<td>
<input id="rate_rent" class="form-control" name="rent" type="text">
</td>
</tr>
</tbody>
</table>
i want to read the values from text box i tried
var values = {};
$('.v input').each(function () {
values[$(this).attr('name')] = $(this).val();
});
and
$('input[name="fromdays"],[name="todays"],[name="rent"]').each(function () {
var fromdays = $(this).val();
alert(fromdays);
});
I want to store the values in independent variables how do i do that ex all fromdays to firstvariable, all todays to second variable
how do i do that
Thanks
var values = [];
$('.v input').each(function () {
values.push($(this).attr('name') = $(this).val());
});
You can store the values in three different arrays by checking the name attribute of the input fields
var fromdays=new Array();
var todays=new Array();
var rent=new Array();
$('#rate_table input[type="text"]').each(function () {
if($(this).attr('name')=="fromdays")
fromdays.push($(this).val())
if($(this).attr('name')=="todays")
todays.push($(this).val())
if($(this).attr('name')=="rent")
rent.push($(this).val())
});
JsFiddle
On button click, iterate over the inputs and push their values in to the respective array:
$(document).on('click', '#getVar', function() {
var fromVar = [];
var toVar = [];
$('input[name=fromdays]').each(function() {
fromVar.push($(this).val());
});
$('input[name=todays]').each(function() {
toVar.push($(this).val());
});
alert('from: ' + fromVar + ' - to: ' + toVar);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table class="table ratemanagement customtabl-bordered " id="rate_table">
<tbody>
<tr>
<th><input type="checkbox" onclick="select_all()" class="check_all"></th>
<th>From Days*</th>
<th>To Days*</th>
<th>Rent*</th>
</tr>
<tr>
<td>
<input class="case" type="checkbox">
</td>
<td class="v">
<input id="rate_fromdays" class="form-control" name="fromdays" type="text">
</td>
<td>
<input id="rate_todays" class="form-control" name="todays" type="text">
</td>
<td>
<input id="rate_rent" class="form-control" name="rent" type="text">
</td>
</tr>
<tr>
<td>
<input class="case" type="checkbox">
</td>
<td class="v">
<input id="rate_fromdays" class="form-control" name="fromdays" type="text">
</td>
<td>
<input id="rate_todays" class="form-control" name="todays" type="text">
</td>
<td>
<input id="rate_rent" class="form-control" name="rent" type="text">
</td>
</tr>
</tbody>
</table>
<button id="getVar">get variables</button>
I am trying to create an array from the content of a table. The content of the tables looks something like this:
<table>
<tr class="rowUpdate">
<td>Corredor Feed</td>
<td>Id Corrdor
<input type="text" value="" class="validate" name="idcorreo">
</td>
<td>Nombre
<input type="text" value="" class="validate" name="nombre">
</td>
<td>Email
<input type="text" value="foo#bar.com" class="validate" name="email">
</td>
<td>Empressa
<input type="text" value="" class="validate" name="Empressa">
</td>
<td>Pagina Web
<input type="text" value="" class="validate" name="paginaWeb">
</td>
<td>Telefono
<input type="text" value="" class="validate" name="telephon">
</td>
<td>Cellular
<input type="text" value="" class="validate" name="cellular" />
</td>
<td>
<input type="submit" id="guardarBtn" value="Save" name="submitme">
</td>
</tr>
</table>
And the script that I have written is like this
$(document).on('click', '#guardarBtn', function (event) {
var content=[];
$('.rowUpdate').each(function (i) {
$(this).find('td').each(function (j, v) {
if (j != 0) {
var input = $("input", this),
name = input.attr("name").substring(0, input.attr("name").length),
value = input.val();
alert(value);
content[name] = value;
alert(JSON.stringify(content));
}
});
//alert(content);
rows.push(content);
});
});
But when I click on the button to get the content of the columns of the table and save it in an array it shows blank
UPDATED Js Fiddle link is here
Thanks in advance
Check this one. I changed var content= []; to var content= {};
$(document).on('click', '#guardarBtn', function (event) {
var content= {};
$('.rowUpdate').each(function (i) {
$(this).find('td').each(function (j, v) {
if (j != 0) {
var input = $("input", this),
name = input.attr("name").substring(0, input.attr("name").length),
value = input.val();
content[name] = value;
// alert(JSON.stringify(content));
}
});
alert(JSON.stringify(content));
// rows.push(content);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr class="rowUpdate">
<td>Corredor Feed</td>
<td>Id Corrdor
<input type="text" value="" class="validate" name="idcorreo">
</td>
<td>Nombre
<input type="text" value="" class="validate" name="nombre">
</td>
<td>Email
<input type="text" value="foo#bar.com" class="validate" name="email">
</td>
<td>Empressa
<input type="text" value="" class="validate" name="Empressa">
</td>
<td>Pagina Web
<input type="text" value="" class="validate" name="paginaWeb">
</td>
<td>Telefono
<input type="text" value="" class="validate" name="telephon">
</td>
<td>Cellular
<input type="text" value="" class="validate" name="cellular" />
</td>
<td>
<input type="submit" id="guardarBtn" value="Save" name="submitme">
</td>
</tr>
</table>
Try this (keep the HTML the same):
$(document).on('click', '#guardarBtn', function (event) {
var rows = [];
$('.rowUpdate').each(function (i) {
var row = {};
$(this).find('td').each(function (j, v) {
if (j != 0) {
var input = $("input", this),
name = input.attr("name").substring(0, input.attr("name").length),
value = input.val();
row[name] = value;
}
rows.push(row);
});
});
Shorter way to access :
$(document).on('click', '#guardarBtn', function (event) {
var content = {};
$('.rowUpdate').each(function (i) {
$(this).find('input[type=text]').each(function(){
content[$(this).attr("name")] = $(this).val();
});
});
alert(JSON.stringify(content));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr class="rowUpdate">
<td>Corredor Feed</td>
<td>Id Corrdor
<input type="text" value="" class="validate" name="idcorreo">
</td>
<td>Nombre
<input type="text" value="" class="validate" name="nombre">
</td>
<td>Email
<input type="text" value="foo#bar.com" class="validate" name="email">
</td>
<td>Empressa
<input type="text" value="" class="validate" name="Empressa">
</td>
<td>Pagina Web
<input type="text" value="" class="validate" name="paginaWeb">
</td>
<td>Telefono
<input type="text" value="" class="validate" name="telephon">
</td>
<td>Cellular
<input type="text" value="" class="validate" name="cellular" />
</td>
<td>
<input type="submit" id="guardarBtn" value="Save" name="submitme">
</td>
</tr>
</table>
Try This :
<form name="form_name" id='form_name'>
<table>
<tr class="rowUpdate">
<td>Corredor Feed</td>
<td>Id Corrdor
<input type="text" value="" class="validate" name="idcorreo">
</td>
<td>Nombre
<input type="text" value="" class="validate" name="nombre">
</td>
<td>Email
<input type="text" value="foo#bar.com" class="validate" name="email">
</td>
<td>Empressa
<input type="text" value="" class="validate" name="Empressa">
</td>
<td>Pagina Web
<input type="text" value="" class="validate" name="paginaWeb">
</td>
<td>Telefono
<input type="text" value="" class="validate" name="telephon">
</td>
<td>Cellular
<input type="text" value="" class="validate" name="cellular" />
</td>
<td>
<input type="submit" id="guardarBtn" value="Save" name="submitme">
</td>
</tr>
</table>
</form>
js Here :
$(document).on('click', '#guardarBtn', function (event) {
var row=[];
$('.rowUpdate').each(function (i) {
var content=[];
$(this).find('input').each(function(key,value){
var field_name=$(this).attr('name');
var field_value=$(this).val();
content[field_name]=field_value;
});
row.push(content);
});
console.log(row);
});
If I well understand the question, you just need for something like this (I'm not sure however why you used nested each loops - is there any reason of this? Do you have more code in between these loops?)
$(document).on('click', '#guardarBtn', function(e){
var content={};
$('.rowUpdate td').find('input').each(function(){
content[this.name] = this.value;
});
alert(JSON.stringify(content));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr class="rowUpdate">
<td>Corredor Feed</td>
<td>Id Corrdor
<input type="text" value="" class="validate" name="idcorreo">
</td>
<td>Nombre
<input type="text" value="" class="validate" name="nombre">
</td>
<td>Email
<input type="text" value="foo#bar.com" class="validate" name="email">
</td>
<td>Empressa
<input type="text" value="" class="validate" name="Empressa">
</td>
<td>Pagina Web
<input type="text" value="" class="validate" name="paginaWeb">
</td>
<td>Telefono
<input type="text" value="" class="validate" name="telephon">
</td>
<td>Cellular
<input type="text" value="" class="validate" name="cellular" />
</td>
<td>
<input type="submit" id="guardarBtn" value="Save" name="submitme">
</td>
</tr>
</table>
I have input fields like this
<input name="unittotal[]" type="text" id="unittotal[]" onchange="sumofunittotal();" size="3" />
<input name="unittotal[]" type="text" id="unittotal[]" onchange="sumofunittotal();" size="3" />
<input name="unittotal[]" type="text" id="unittotal[]" onchange="sumofunittotal();" size="3" />
<input name="unittotal[]" type="text" id="unittotal[]" onchange="sumofunittotal();" size="3" />
.
.
.
<input name="total" type="text" id="total" value="">
if i enter value in unittotal field onchange the final text box value is should be sum of that unit total using javascript.
Here's the working demo for you.
You need not use duplicate id values for your HTML elements. Consider using class name instead. Refer the markup and the code that calculates the total. I hope its self-explanatory enough.
JavaScript:
function updateTotal() {
var total = 0;//
var list = document.getElementsByClassName("input");
var values = [];
for(var i = 0; i < list.length; ++i) {
values.push(parseFloat(list[i].value));
}
total = values.reduce(function(previousValue, currentValue, index, array){
return previousValue + currentValue;
});
document.getElementById("total").value = total;
}
HTML:
<input type="text" class='input' value="0" onchange='updateTotal();'>
<input type="text" class='input' value="0" onchange='updateTotal();'>
<input type="text" class='input' value="0" onchange='updateTotal();'>
<input type="text" class='input' value="0" onchange='updateTotal();'>
<input name="total" type="text" id="total" value="">
Like this:
<input type="text" size="3" class="add" />
<input type="text" size="3" class="add" />
<input type="text" size="3" class="add" />
<input type="text" size="3" class="add" />
<hr>
<input type="text" size="3" id="sum" />
and the javascript:
(function () {
var elms = document.querySelectorAll('.add'),
arr = Array.prototype.slice.call(elms),
onChange = function () {
var result = 0;
arr.forEach(function (el) {
result = result + +el.value;
});
document.getElementById('sum').value = result;
};
arr.forEach(function (el) {
el.addEventListener('change', onChange);
});
}());
http://jsfiddle.net/65b6T/
try this , and see in detail in fiddle DEMO.
HTML
<table width="300px" border="1" style="border-collapse:collapse;background-color:#E8DCFF">
<tr>
<td width="40px">1</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>2</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>3</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>4</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>5</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr>
<td>6</td>
<td>
<input class="txt" type="text" name="txt" />
</td>
</tr>
<tr id="summation">
<td align="left">Total :</td>
<td align="left"><span id="sum">0</span>
</td>
</tr>
</table>
Javascript:
$(document).ready(function () {
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".txt").each(function () {
$(this).keyup(function () {
calculateSum();
});
});
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".txt").each(function () {
//add only if the value is number
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sum").html(sum.toFixed(2));
}
Here is a DEMO for this solution. http://jsfiddle.net/jxJg7/1/
NOTES:
It works only if your values are integers.
I created a function that will force the user to put numbers only on the inputs
Make sure you remove the duplicated IDs
<script type="text/javascript">
function sumofunittotal() {
var total = 0;
var cusid_ele = document.getElementsByClassName('inputtosum');
for (var i = 0; i < cusid_ele.length; ++i) {
if (!isNaN(parseInt(cusid_ele[i].value)) )
total += parseInt(cusid_ele[i].value);
}
document.getElementById('total').value=total;
}
function onlynumber(e) {
if (e.shiftKey === true ) {
if (e.which == 9) {
return true;
}
return false;
}
if (e.which > 57) {
return false;
}
if (e.which==32) {
return false;
}
return true;
}
</script>
<input name="unittotal[]" class="inputtosum" type="text" onchange="sumofunittotal();" onkeydown="return onlynumber(event);" size="3" />
<input name="unittotal[]" class="inputtosum" type="text" onchange="sumofunittotal();" onkeydown="return onlynumber(event);" size="3" />
<input name="unittotal[]" class="inputtosum" type="text" onchange="sumofunittotal();" onkeydown="return onlynumber(event);" size="3" />
<input name="unittotal[]" class="inputtosum" type="text" onchange="sumofunittotal();" onkeydown="return onlynumber(event);" size="3" />
<input name="total" type="text" id="total" value="">