krushio vida krushio vida - 4 months ago 8
HTML Question

Add total from rows using javascript

I want to add the total of values in the table below but with some conditions which i dont know how to implement

<table id="tableID" width="200" border="1">
<tr>
<td class="compulsory">5</td>
<td class="compulsory">8</td>
<td class="compulsory">8</td>

<td class="one">8</td>
<td class="one">7</td>
<td class="one">6</td>

<td class="two">9</td>
<td class="two">4</td>

<td class="total"></td>
</tr>
</table>


The conditions are;


Table data with class compulsory must be added

Table data with class one pick the highest two values

Table data with class two pick the highest one value


Then display the total in the Table data with class total

Answer

How about below solution, you can refactor further if needed.

<html>
<body>
    <table border="1" id="tableID" width="200">
        <tr>
            <td class="compulsory">5</td>
            <td class="compulsory">8</td>
            <td class="compulsory">8</td>
            <td class="one">8</td>
            <td class="one">7</td>
            <td class="one">6</td>
            <td class="two">9</td>
            <td class="two">4</td>
            <td class="total"></td>
        </tr>
    </table>
</body>
<script type="text/javascript">
var table = document.getElementById('tableID');
var tr = table.getElementsByTagName('tr')[0];
var tdsCompulsory = tr.getElementsByClassName('compulsory');
var tdsOne = document.getElementsByClassName('one');
var tdsTwo = document.getElementsByClassName('two');

var cData = [];
var oneData = [];
var twoData = [];
var sum = 0;

for(var i in tdsCompulsory){
    if(typeof tdsCompulsory[i].textContent != 'undefined')
    cData.push(tdsCompulsory[i].textContent);
}
for(var i in tdsOne){
    if(typeof tdsOne[i].textContent != 'undefined')
    oneData.push(tdsOne[i].textContent);
}
for(var i in tdsTwo){
    if(typeof tdsTwo[i].textContent != 'undefined')
    twoData.push(tdsTwo[i].textContent);
}
console.log(cData);
console.log(oneData);
console.log(twoData);

for(var i in cData){
    sum +=parseInt(cData[i]);
}

var maxOne=0, maxTwo=0;
for(var i in oneData){
        if(maxOne < parseInt(oneData[i])){
            maxTwo = maxOne;
            maxOne = parseInt(oneData[i]);
        } else if(maxTwo < parseInt(oneData[i])){
            maxTwo = parseInt(oneData[i]);
        }
}
sum += maxOne + maxTwo;

var max = 0;
for(var i in twoData){
    if(max < parseInt(twoData[i])){
        max = parseInt(twoData[i]);
    }
}
console.log(max);    
sum +=max;
console.log(sum);    
document.getElementsByClassName('total')[0].textContent = sum;
</script>
</html>