Title: Using javascript to take the lowest two numbers from the total of a table row
Tags: javascript;html;arrays
Question: I am attempting to write a page which has a table where the user can input a number in each cell, it would then display a total of that row with the lowest two values of that row subtracted. The code creates the array, finds the total of the array and the lowest 2 values (low and low2 in the code below). However when I try to take the two lowest values from the total, i get an error. I think i have found the error as testing the values using isNaN i find that the sum of the array is not a number, which doesn't seem to make sense to me. Here is where I got up to with the code:
table = document.getElementsByTagName("tbody")[0];
allrows = table.getElementsByTagName("tr");
for (i=0; i < allrows.length; i++) {
rowTotal = 0;
rowArray =[];
for (ii=0; ii < allrows[i].getElementsByTagName("input").length; ii++) {
rowTotal = rowTotal + Number(allrows[i].getElementsByTagName("input")[ii].value);
rowArray.push(Number(allrows[i].getElementsByTagName("input")[ii].value));
var tots=rowTotal;
}
rowArray.sort(function(a, b){return b-a});
var low = $(rowArray[rowArray.length-2]);
var low2 = $(rowArray[rowArray.length-1]);
rowTotaladj = rowTotal- low  - low2;
$(".row-total:eq("+(i-1)+")").html(rowTotaladj);
Here is a link to a previous version of the page which correctly displays the total (rowTotal) but does not have the total minus the lowest two values in:
Any explaination as to why the sum is not a number and help with the code would be much appreciated.
Comment: `parseInt()` is your friend.


Here is another answer: Since you're already using jQuery, you can use the following code to achieve what you want:
// When an <input&gt; is changed:
$('table input').on('change', function() {
var sum = 0,
vals = [  ];
$(this).parents('table').find('input').each(function() {
var val = parseInt( $(this).val() ) || 0;
vals.push( val );
sum+= val;
});
// Now sort the array:
vals.sort();
total = sum - vals[0] - vals[1];
$('tfoot td').html( total );
jsFiddle Demo
Comment for this answer: Thank you so much, you are a star!

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 1, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2015:00:08/23/15', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<javascript><html><arrays>', 'Title': 'Using javascript to take the lowest two numbers from the total of a table row', 'ViewCount': 61, 'id': 32170750, 'user_AboutMe': None, 'user_AccountId': 3589738.0, 'user_DisplayName': 'user2996079', 'user_Reputation': 21.0, 'user_Views': 1.0, 'user_id': 2996079.0}}