Andrew Bailey Andrew Bailey - 6 months ago 14
Javascript Question

Multiple functions for eventListener Callback

I have this html table and span. I am trying to make it so that on each row value1 and value2 will add together and display in the sum cell in the same row. Also so that each value for value1, value2, and Sum in both row 1 and in row 2 will add together and display in the span for that specific column.

I know for the rows it would be easy, but can I have multiple functions for the JavaScript event listeners on a single element, one would do the calculation for the column and the other would do the calculation for rows. Or should I be using a library (eg. knockoutJS)

<table style="border: 1px solid">
<thead style="border: 1px solid">
<th>
Value 1
</th>
<th>
Value 2
</th>
<th>
Sum
</th>
</thead>
<tr>
<td id="r1c1">
<input style="width:50px" />
</td>
<td id="r1c2">
<input style="width:50px" />
</td>
<td id="r1c3">
<span id="r1Sum">0</span>
</td>
</tr>
<tr>
<td id="r2c1">
<input style="width:50px"/>
</td>
<td id="r2c2">
<input style="width:50px"/>
</td>
<td id="r2c3">
<span id="r2Sum">0</span>
</td>
</tr>
</table>
Value 1 column total: <span id="val1ColTotal">0</span>
&nbsp;
Value 2 column total: <span id="val2ColTotal">0</span>
&nbsp;
Sum column total: <span id="sumColTotal">0</span>


JSFIDDLE https://jsfiddle.net/gauldivic/4002h1wj/2/

Answer
  • calling 2 functions (with calculations and ui update) from the callback

https://jsfiddle.net/emv8tbLb/


 <td>
    <input style="width:50px" />
  </td>
  <td>
    <input style="width:50px" />
  </td>
  <td>
    <span id="sum">0</span>
  </td>

function sumRows(){
   $('tr').each(function() {
     var sum = 0;
     $(this).find('input').each(function() {
       sum += +parseFloat($(this).val()) || 0;
     });
     $("#sum", this).text(sum);
   });
}

function sumColumns(){
 //...
}

$("table").bind("keyup", function() {
  sumRows(this);
  sumColumns(this);
});

  • multiple event listeners can be added to the element (using jquery)

$("table").bind("keydown, keyup", function() {...
Comments