How do I sum the two highest values from a list of inputs using JavaScript?
I've tried the below, but I get 4 instead of 5:
<table id="tableID">
<tr>
<td> <input name="name" class="compulsory1" type="text" value="1" /> </td>
<td> <input name="name1" class="compulsory1" type="text" value="3" /> </td>
<td> <input name="name2" class="compulsory1" type="text" value="2" /> </td>
<td>
<script type="text/javascript">
var tdsCompulsory = document.getElementsByClassName('compulsory1');
var len = tdsCompulsory.length;
var cDatax = [];
var cData = cDatax.reverse();
sum = 0;
for(var i = 0; i < 2; i++){
cData.push(tdsCompulsory[i].value);
sum += +tdsCompulsory[i].value;
}
alert (sum);
</script>
</td>
</tr>
</table>
First you find the two highest values, and then sum them together. I'd probably do it something like this:
document.getElementById("the-button").onclick = function() {
// Get the values as numbers
var values = Array.prototype.map.call(
document.getElementsByClassName('compulsory1'),
function(input) {
return +input.value; // + converts to number
}
);
// Put them in order *highest* to *lowest*
values.sort(function(left, right) {
return right - left;
});
// Add the first two
var result = values[0] + values[1];
console.log(values[0] + " + " + values[1] + " = " + result);
};
<input name="name" class="compulsory1" type="text" value="1" />
<input name="name1" class="compulsory1" type="text" value="3" />
<input name="name2" class="compulsory1" type="text" value="2" />
<input id="the-button" type="button" value="Run">
More about that Array.prototype.map.call thing in this answer about looping through arrays and array-like things.
But if you specifically want to use reverse, you'd do that after the sort:
document.getElementById("the-button").onclick = function() {
// Get the values as numbers
var values = Array.prototype.map.call(
document.getElementsByClassName('compulsory1'),
function(input) {
return +input.value; // + converts to number
}
);
// Put them in order lowest to highest
values.sort(function(left, right) {
return left - right;
});
// Then reverse that
values.reverse();
// Add the first two
var result = values[0] + values[1];
console.log(values[0] + " + " + values[1] + " = " + result);
};
<input name="name" class="compulsory1" type="text" value="1" />
<input name="name1" class="compulsory1" type="text" value="3" />
<input name="name2" class="compulsory1" type="text" value="2" />
<input id="the-button" type="button" value="Run">
You could try something like following:
function PickTwoHighestCtrl() {
let els = document.querySelectorAll(".compulsory1");
let values = Array.prototype.map.call(els, (el) => {
return Number(el.value) || 0;
});
let highest = Math.max.apply(Math, values);
let secondHighest = Math.max.apply(
Math, values.filter(e => e !== highest)
);
console.log("Two highest values are:", highest, secondHighest, "and their sum is", highest + secondHighest)
}
document.addEventListener("DOMContentLoaded", PickTwoHighestCtrl);
<input class="compulsory1" type="text" value="1" />
<input class="compulsory1" type="text" value="3" />
<input class="compulsory1" type="text" value="2" />
Check this fiddle
<html>
<head>
<script>
var tdsCompulsory = document.getElementsByClassName('compulsory1');
var cDatax = [];
sum = 0;
for(var i = 0; i < 3; i++){
cDatax.push(tdsCompulsory[i].value);
}
// let's convert it to a real array of numbers, not of strings :
var intArray = cDatax.map(Number);
var max = Math.max.apply(null, intArray);
// now let's sort it and take the second element :
var second = intArray.sort(function(a,b){return b-a})[1];
var sum = max+second;
alert(sum)
</script>
</head>
<body>
<table id="tableID">
<tr>
<td> <input name="name" class="compulsory1" type="text" value="1" /> </td>
<td> <input name="name1" class="compulsory1" type="text" value="3" /> </td>
<td> <input name="name2" class="compulsory1" type="text" value="2" /> </td>
<td>
</td>
</tr>
</table>
</body>
</html>
You can try something like this:
Steps
Get all elements
Get their values. Note, since you expect values to be number, yuo should parse them as well.
Sort value array in descending order instead of .sort + .reverse
Calculate your sum
Sample
// Get all elements
var tdsCompulsory = document.getElementsByClassName('compulsory1');
// Get values from all elements
var valArr = Array.prototype.map.call(tdsCompulsory, function(el) {
return parseInt(el.value)
});
// Sort value array in descending order
var cDatax = valArr.sort(function(a, b) {
return b-a
});
var sum = cDatax[0] + cDatax[1];
console.log(sum)
<table id="tableID">
<tr>
<td>
<input name="name" class="compulsory1" type="text" value="1" />
</td>
<td>
<input name="name1" class="compulsory1" type="text" value="3" />
</td>
<td>
<input name="name2" class="compulsory1" type="text" value="2" />
</td>
</tr>
</table>
var tdsCompulsory = document.getElementsByClassName('compulsory1'),
cDatax = Array.prototype.map.call(tdsCompulsory, function(el) {
return parseInt(el.value) || 0;
}),
sum = 0;
cDatax
.sort(function(a, b){
return a - b;
})
.reverse();
sum = cDatax[0] + cDatax[1];
console.log(sum);
<table id="tableID">
<tr>
<td><input name="name" class="compulsory1" type="text" value="1" /></td>
<td><input name="name1" class="compulsory1" type="text" value="3" /></td>
<td><input name="name2" class="compulsory1" type="text" value="2" /></td>
</tr>
</table>
Related
I am trying to highlight a value in a div that is the lowest value in an array.
When the user completes each input row (design outlet and actual outlet) the outletIndex() function is called which calculates the percentage and pushes the value into an array. This part I have working.
Then what I am trying to do is find the lowest number in that array and highlight the div (proportion). I want this to be dynamic so as the user completes each input row the percentage is calculated and the lowest index value is highlighted progressively.
I am using querySelectorAll() to match the div class value to the lowest index value but Im not sure if I need to parse a nodeList to match the value of the indexArray?
I am also wondering that if a mistake is typed into the fields and added to the Index array and it happens to be the lowest index it wont match the index values that are shown on the HTML and not call the function.
document.querySelector('#outlet_actual_1').addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
let actual = document.getElementById("outlet_actual_1").valueAsNumber || 0;
let design = document.getElementById("outlet_design_1").valueAsNumber || 0;
let result1 = outletIndex(actual, design);
if (!isNaN(result1)) {
document.getElementById("percentage").textContent = `${result1.toFixed(1)}%`;
}
}
});
document.querySelector('#outlet_actual_2').addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
let actual = document.getElementById("outlet_actual_2").valueAsNumber || 0;
let design = document.getElementById("outlet_design_2").valueAsNumber || 0;
let result1 = outletIndex(actual, design);
if (!isNaN(result1)) {
document.getElementById("percentage2").textContent = `${result1.toFixed(1)}%`;
}
}
});
document.querySelector('#outlet_actual_3').addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
let actual = document.getElementById("outlet_actual_3").valueAsNumber || 0;
let design = document.getElementById("outlet_design_3").valueAsNumber || 0;
let result1 = outletIndex(actual, design);
if (!isNaN(result1)) {
document.getElementById("percentage3").textContent = `${result1.toFixed(1)}%`;
}
}
});
const indexArray = [];
function outletIndex(a, b) {
let result = a / b * 100;
if (!isNaN(result)) {
indexArray.push(+result.toFixed(2));
indexFindandHighlight();
}
console.log(indexArray, result);
return result;
}
function indexFindandHighlight(){
const lowestIndex = Math.min(...indexArray);
const indexCheck = document.querySelectorAll('.proportion').valueAsNumber || 0;
console.log(lowestIndex);
if (lowestIndex == indexCheck) {
$(document).ready(function() {
$("#outlet_actual_1", "#outlet_actual_2", "#outlet_actual_3").onchange(function(){
$(".proportion").effect( "highlight", {color:"#669966"}, 3000 );
});
});
}
};
<table>
<tr>
<div class="form-group row 1" id="outlets1">
<td><label
>Outlet Design</label>
<input
name = "outlet 1 design"
class="form-control design_1"
id="outlet_design_1"
type="number"
placeholder="Outlet 1 Design"
onkeydown="outletIndex();"
/>
</td>
<td><label
>Outlet Actual</label>
<input
name="outlet 1 actual"
class="form-control actual_1"
id="outlet_actual_1"
type="number"
placeholder="Outlet 1 Actual"
onkeydown="outletIndex();"
/>
</td>
<td><label
>Outlet Balance</label>
<input
name="outlet_balance"
class="form-control"
input value=""
id="outlet_balance_1"
type="text"
placeholder="Outlet 1 Balance"
/>
</td><td>
<div class="proportion" id="percentage">
</div>
</td>
</div>
</tr>
<tr>
<div class="form-group row 2" id="outlets2">
<td>
<input
name="outlet_design"
class="form-control design_2"
id="outlet_design_2"
type="number"
placeholder="Outlet 2 Design"
onkeydown="outletIndex();"
/>
</td>
<td>
<input
name="outlet_actual"
class="form-control actual_2"
id="outlet_actual_2"
type="number"
placeholder="Outlet 2 Actual"
onkeydown="outletIndex();"
/>
</td>
<td>
<input
name="outlet_balance"
class="form-control"
id="outlet_balance_2"
type="number"
placeholder="Outlet 2 Balance"
/>
</td><td>
<div class="proportion" id="percentage2">
</div>
</td>
</div></tr>
<tr>
<div class="form-group row 3" id="outlets3">
<td>
<input
name="outlet_design"
class="form-control design_3"
id="outlet_design_3"
type="number"
placeholder="Outlet 3 Design"
onkeydown="outletIndex();"
/>
</td>
<td>
<input
name="outlet_actual"
class="form-control actual_3"
id="outlet_actual_3"
type="number"
placeholder="Outlet 3 Actual"
onkeydown="outletIndex();"
/>
</td>
<td>
<input
name="outlet_balance"
class="form-control"
id="outlet_balance_3"
type="number"
placeholder="Outlet 3 Balance"
/>
</td><td>
<div class="proportion" id="percentage3">
</div>
</td>
</div></tr>
</div>
</table>
</fieldset>
</form>
</div>
Multiple issues:
Clean up HTML
Reuse code
Consistency, Either use jquery or javascript
Separate UI changes from data change.
Consistency, Bind event listener either using HTML or javascript file.
Please check below sample
const number = (str) => Number(str) || 0;
const bind = (id) => {
function onBind(e) {
let actual = number(document.querySelector(`#outlet_actual_${id}`).value);
let design = number(document.querySelector(`#outlet_design_${id}`).value);
let result1 = percentage(actual, design);
if (!isNaN(result1)) {
document.querySelector(
`#percentage_${id}`
).textContent = `${result1.toFixed(1)}%`;
}
updateIndex(id, result1);
highlight();
}
document
.querySelector(`#outlet_actual_${id}`)
.addEventListener("change", onBind);
document
.querySelector(`#outlet_design_${id}`)
.addEventListener("change", onBind);
};
function percentage(a, b) {
return b === 0 ? 0 : (a / b) * 100;
}
let percentages = [];
function updateIndex(id, value) {
percentages[id - 1] = value;
}
function highlight() {
let minIndex = -1;
let minValue = Number.MAX_SAFE_INTEGER;
for (let index in percentages) {
if (percentages[index] < minValue) {
minIndex = Number(index);
minValue = percentages[index];
}
}
if (minIndex === -1) return;
document.querySelector(`#percentage_${minIndex + 1}`).style.color = "red";
setTimeout(() => {
document.querySelector(`#percentage_${minIndex + 1}`).style.color = "black";
}, 3000);
}
bind(1);
bind(2);
bind(3);
<table>
<tr>
<div class="form-group row 1" id="outlets1">
<td><label
>Outlet Design</label>
<input
name = "outlet 1 design"
class="form-control design_1"
id="outlet_design_1"
type="number"
placeholder="Outlet 1 Design"
/>
</td>
<td><label
>Outlet Actual</label>
<input
name="outlet 1 actual"
class="form-control actual_1"
id="outlet_actual_1"
type="number"
placeholder="Outlet 1 Actual"
/>
</td>
<td><label
>Outlet Balance</label>
<input
name="outlet_balance"
class="form-control"
input value=""
id="outlet_balance_1"
type="text"
placeholder="Outlet 1 Balance"
/>
</td><td>
<div class="proportion" id="percentage_1">
</div>
</td>
</div>
</tr>
<tr>
<div class="form-group row 2" id="outlets2">
<td>
<input
name="outlet_design"
class="form-control design_2"
id="outlet_design_2"
type="number"
placeholder="Outlet 2 Design"
/>
</td>
<td>
<input
name="outlet_actual"
class="form-control actual_2"
id="outlet_actual_2"
type="number"
placeholder="Outlet 2 Actual"
/>
</td>
<td>
<input
name="outlet_balance"
class="form-control"
id="outlet_balance_2"
type="number"
placeholder="Outlet 2 Balance"
/>
</td><td>
<div class="proportion" id="percentage_2">
</div>
</td>
</div></tr>
<tr>
<div class="form-group row 3" id="outlets3">
<td>
<input
name="outlet_design"
class="form-control design_3"
id="outlet_design_3"
type="number"
placeholder="Outlet 3 Design"
/>
</td>
<td>
<input
name="outlet_actual"
class="form-control actual_3"
id="outlet_actual_3"
type="number"
placeholder="Outlet 3 Actual"
/>
</td>
<td>
<input
name="outlet_balance"
class="form-control"
id="outlet_balance_3"
type="number"
placeholder="Outlet 3 Balance"
/>
</td><td>
<div class="proportion" id="percentage_3">
</div>
</td>
</div></tr>
</div>
</table>
</fieldset>
</form>
</div>
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>
Trying to calculate a selection value from a radio group and values from other fields. Any 'Name' input adds a value to the Total. I need the value from the radio group to be added to that total.
Here is the HTML:
<FORM NAME="testauthorization" ACTION="" METHOD=POST id="exhibitreg">
<table>
<tr>
<td><label>
<input type="radio" name="sponsorship" value="3000" id="sponsor1" />
$3,000</label>
<br />
<label>
<input type="radio" name="sponsorship" value="1500" id="sponsor2" />
$1,500</label>
<br />
<label>
<input type="radio" name="sponsorship" value="1000" id="sponsor3" />
$1,000</label>
<br /></td>
</tr>
<tr>
<td>Name 1 <INPUT NAME="Name_1" TYPE="TEXT" id="name1" onchange="updatecost(1, 50)" onkeyup="updatecost(1, 50)" VALUE="" size="30"></td>
<td><INPUT NAME="cost_1" TYPE="TEXT" VALUE="" size="4" id="cost1"></td>
</tr>
<tr>
<td>Name 2<INPUT NAME="Name_2" TYPE="TEXT" id="name2" onchange="updatecost(2, 50)" onkeyup="updatecost(2, 50)" VALUE="" size="30"></td>
<td><INPUT NAME="cost_2" TYPE="TEXT" VALUE="" size="4" id="cost2"></td>
</tr>
<tr>
<td>Name 3<INPUT NAME="Name_3" TYPE="TEXT" id="name3" onchange="updatecost(3, 50)" onkeyup="updatecost(3, 50)" VALUE="" size="30"></td>
<td><INPUT NAME="cost_3" TYPE="TEXT" VALUE="" size="4" id="cost3"></td>
</tr>
<tr>
<td colspan="4">Total:
<INPUT NAME="Total" id="Total" TYPE="TEXT" VALUE="" size="8" onFocus="this.form.elements[0].focus()" >
<INPUT TYPE="HIDDEN" onchange="totalcost()" onkeyup="totalcost()"></td>
</tr>
</table>
<INPUT TYPE="SUBMIT" VALUE="Submit">
<input type="RESET" name="Reset" value="Reset" />
</FORM>
And here is the JS:
<script language="JavaScript" type="text/javascript">
function getRadioValue(name) {
var group = document.getElementsByName('sponsorship');
for (var i=0;i<group.length;i++) {
if (group[i].checked) {
return group[i].value;
}
}
return '';
}
function updatecost(num, dollars) {
var text = document.getElementById("name" + num);
var cost = document.getElementById("cost" + num);
if (!text) return;
if (!cost) return;
if (text.value == "") {
cost.value = "";
}
else {
cost.value = dollars;
}
totalcost();
}
function totalcost() {
var total = 0;
for (var i = 1; i <= 3; i++) {
var cost = document.getElementById("cost" + i);
if (cost.value) total += Number(cost.value);
}
document.getElementById("Total").value = total;
}
//-->
</script>
What am I missing? By the way, in case it is not clear, I am a JS novice, so I fully accept criticism that helps me understand a more fundamental error in my approach. Simple is best for me: ;-) Thank you in advance.
Change below function in place of existing
function updatecost(num, dollars) {
var text = document.getElementById("name" + num);
var cost = document.querySelector('input[name="sponsorship"]:checked');
if (!text) return;
if (!cost) return;
totalcost(cost);
}
function totalcost(cost) {
var total = 0;
for (var i = 1; i <= 3; i++) {
var text1 = document.getElementById("name" + i);
if (text1.value != "") total += Number(cost.value);
}
document.getElementById("Total").value = total;
}
I am having table below.. but Getting wrong calculation in javascript..
<script>
function getPrice(tRate, tMaking, tHandeling, tPrice, tVat, tQuantity, tTotal) {
var obj_tRate = document.getElementById(tRate)
var obj_tMaking = document.getElementById(tMaking)
var obj_tHandeling = document.getElementById(tHandeling)
var obj_tPrice = document.getElementById(tPrice)
var obj_tVat = document.getElementById(tVat)
var obj_tTotal = document.getElementById(tTotal)
var obj_tQuantity = document.getElementById(tQuantity)
if (obj_tRate.value != "" && obj_tMaking.value != "" && obj_tHandeling.value != "") {
obj_tPrice.value = parseFloat(obj_tRate.value) + parseFloat(obj_tMaking.value) + parseFloat(obj_tHandeling.value);
console.log(obj_tPrice.value)
obj_tVat.value = parseFloat(obj_tPrice.value * (1 / 100));
console.log(obj_tVat.value)
obj_tTotal.value = parseFloat(obj_tVat.value + (obj_tPrice.value * obj_tQuantity.value));
console.log(obj_tTotal.value)
}
else {
obj_tPrice.value = "";
}
}
</script>
</head>
<body>
<table>
<tr>
<td>
<input name="grdView$ctl08$txtWaight_F" type="text" id="grdView_ctl08_txtWaight_F" class="classWaight" style="width:60px;" />
</td><td>
<input name="grdView$ctl08$txtQuantity_F" type="text" maxlength="20" id="grdView_ctl08_txtQuantity_F" class="classQuantity" onchange="javascript:return getPrice('grdView_ctl08_txtRate_F','grdView_ctl08_txtMaking_F','grdView_ctl08_txtHandeling_F','grdView_ctl08_txtPrice_F','grdView_ctl08_txtvat_F','grdView_ctl08_txtQuantity_F','grdView_ctl08_txtTotal_F');" style="width:60px;" />
</td><td>
<input name="grdView$ctl08$txtRate_F" type="text" maxlength="8" id="grdView_ctl08_txtRate_F" class="classRate" onchange="javascript:return getPrice('grdView_ctl08_txtRate_F','grdView_ctl08_txtMaking_F','grdView_ctl08_txtHandeling_F','grdView_ctl08_txtPrice_F','grdView_ctl08_txtvat_F','grdView_ctl08_txtQuantity_F','grdView_ctl08_txtTotal_F');" style="width:60px;" />
</td><td>
<input name="grdView$ctl08$txtMaking_F" type="text" id="grdView_ctl08_txtMaking_F" class="classMaking" onchange="javascript:return getPrice('grdView_ctl08_txtRate_F','grdView_ctl08_txtMaking_F','grdView_ctl08_txtHandeling_F','grdView_ctl08_txtPrice_F','grdView_ctl08_txtvat_F','grdView_ctl08_txtQuantity_F','grdView_ctl08_txtTotal_F');" style="width:60px;" />
</td><td>
<input name="grdView$ctl08$txtHandeling_F" type="text" id="grdView_ctl08_txtHandeling_F" class="classHandling" onchange="javascript:return getPrice('grdView_ctl08_txtRate_F','grdView_ctl08_txtMaking_F','grdView_ctl08_txtHandeling_F','grdView_ctl08_txtPrice_F','grdView_ctl08_txtvat_F','grdView_ctl08_txtQuantity_F','grdView_ctl08_txtTotal_F');" style="width:60px;" />
</td><td>
<input name="grdView$ctl08$txtPrice_F" type="text" id="grdView_ctl08_txtPrice_F" class="classPrice" style="width:60px;" />
</td><td>
<input name="grdView$ctl08$txtvat_F" type="text" id="grdView_ctl08_txtvat_F" class="classVat" style="width:60px;" />
</td><td>
<input name="grdView$ctl08$txtTotal_F" type="text" id="grdView_ctl08_txtTotal_F" class="classTotal" style="width:100px;" />
</td><td>
<input name="grdView$ctl08$txtSerial_F" type="text" id="grdView_ctl08_txtSerial_F" class="classSerial" />
</td>
</tr>
</table>
</body>
Use parseFloat on the operands, not on the result of the computation.
For example, replace
obj_tTotal.value = parseFloat(obj_tVat.value + (obj_tPrice.value * obj_tQuantity.value));
with
var tPrice = parseFloat(obj_tPrice.value);
var tQuantity = parseFloat(obj_tQuantity.value);
obj_tTotal.value = tPrice + tPrice * tQuantity;
When you add, like you did, a string and a number, you do a string concatenation.
For example
"1000" + "5" * "100"
gives
"1000" + 500
which is
"1000500"
At this point, it's too late to call parseFloat.
I am using jquery to loop through table rows and save the data. If the table has 200 rows it is performing slow. I am getting the javascript message "Stop Running this script" in IE when I call this method. Following is the code I am using to loop through table rows. Can you please let me know if there is a better way to do this.
function SaveData() {
var $table = $('#' + gridid);
var rows = $table.find('tbody > tr').get();
var transactions = [];
var $row, empno, newTransaction, $rowChildren;
$.each(rows, function(index, row) {
$row = $(row);
$rowChildren = $row.children("td");
if ($rowChildren.find("input[id*=hRV]").val() === '1') {
empno = $rowChildren.find("input[id*=tEmpno]").val();
newTransaction = new Array();
newTransaction[0] = company;
newTransaction[1] = $rowChildren.find("input[id*=tEmpno]").val();
newTransaction[2] = $rowChildren.find("input[id*=tPC]").val();
newTransaction[3] = $rowChildren.find("input[id*=hQty]").val();
newTransaction[4] = $rowChildren.find("input[id*=hPR]").val();
newTransaction[5] = $rowChildren.find("input[id*=tJC]").val();
newTransaction[6] = $rowChildren.find("input[id*=tL1]").val();
newTransaction[7] = $rowChildren.find("input[id*=tL2]").val();
newTransaction[8] = $rowChildren.find("input[id*=tL3]").val();
newTransaction[9] = $rowChildren.find("input[id*=tL4]").val();
newTransaction[10] = $rowChildren.find("input[id*=tL5]").val();
newTransaction[11] = $rowChildren.find("input[id*=tL6]").val();
newTransaction[12] = $rowChildren.find("input[id*=tL7]").val();
newTransaction[13] = $rowChildren.find("input[id*=tL8]").val();
newTransaction[14] = $rowChildren.find("input[id*=tL9]").val();
newTransaction[15] = $rowChildren.find("input[id*=tL10]").val();
newTransaction[16] = $rowChildren.find("input[id*=tSF]").val();
newTransaction[17] = $rowChildren.find("input[id*=tCG]").val();
newTransaction[18] = $rowChildren.find("input[id*=tTF]").val();
newTransaction[19] = $rowChildren.find("input[id*=tWK]").val();
newTransaction[20] = $rowChildren.find("input[id*=tAI]").val();
newTransaction[21] = $rowChildren.find("input[id*=tWC]").val();
newTransaction[22] = $rowChildren.find("input[id*=tPI]").val();
newTransaction[23] = "E";
var record = newTransaction.join(';');
transactions.push(record);
}
});
if (transactions.length > 0) {
var strTransactions = transactions.join('|');
//send data to server
//here ajax function is called to save data.
}
}
The html structure for the table row is like this
<tr class="rgRow" id="ctl00_c_PETV2_1_gB_ctl00__12">
<td>
Delete
</td><td>
<input type="text" value='385 ' id="tEmpno" />
<input name="ctl00$c$PETV2_1$gB$ctl00$ctl28$hRV" type="hidden" id="ctl00_c_PETV2_1_gB_ctl00_ctl28_hRV" value="1" />
<input name="ctl00$c$PETV2_1$gB$ctl00$ctl28$hRC" type="hidden" id="ctl00_c_PETV2_1_gB_ctl00_ctl28_hRC" value="0" />
</td><td style="width:100px;">
<input type="text" value='Barron, Pamela J.' id="tEE" readonly="readonly" />
</td><td>
<input type="text" value='OT ' id="tPC" />
</td><td>
<input type="text" value='7.00' id="tQty" class="right" />
<input type="hidden" name="ctl00$c$PETV2_1$gB$ctl00$ctl28$hQty" id="ctl00_c_PETV2_1_gB_ctl00_ctl28_hQty" value="7.00000" />
</td><td>
<input type="text" value='22.00' id="tPR" class="right" />
<input type="hidden" name="ctl00$c$PETV2_1$gB$ctl00$ctl28$hPR" id="ctl00_c_PETV2_1_gB_ctl00_ctl28_hPR" value="22.000000" />
</td><td>
<input type="text" value='231.00' id="tAmt" class="right" readonly="readonly" />
</td><td>
<input type="text" value='300 ' id="tJC" />
</td><td>
<input type="text" value='50 ' id="tL1" />
</td><td>
<input type="text" value='23 ' id="tL2" />
</td><td>
<input type="text" value='001 ' id="tL3" />
</td><td>
<input type="text" value=' ' id="tL4" />
</td><td>
<input type="text" value='1 ' id="tSF" />
</td><td>
<input type="text" value='1' id="tCG" />
</td><td>
<input type="text" value='B' id="tTF" />
</td><td>
<input type="text" value='0' id="tWk" />
</td><td>
<input type="text" value='Y' id="tAI" />
</td><td>
<input type="text" value='8810 ' id="tWC" />
</td><td style="width:50px;">
<input type="text" value='' id="tPI" />
</td>
</tr>
Try minimizing your use of jQuery find(). Its performance is really bad on older browsers. Perhaps use good old getElementsByTagName() instead, which is implemented natively even on IE6. Pseudocode:
get list of tr elements;
for each tr element:
get list of input elements descending from current tr element;
for each input:
if input.id matches x
if input.id matches y
if input.id matches z
Hope this helps.
Replace the repeated calls to find by splitting out that part of the id and then doing a var index = $.inArray(idFragment, ['', 'tEmpno', 'hQty']); call or similar strategy to determine the input's position in the transaction array.
Make as few searches on the DOM as possible. Prefer |= over *= selectors if possible.
Or, if possible, modify the serialize function in jQuery as needed and use the index of the input to determine its position in the transaction array.