April 29, 2012

Perform Dynamic Table Calculations in HTML – jQuery?

Question by user982124

I have an HTML table which allows the user to enter some values, either directly or from a select menu.

<form action="" method="">
<table id="scores" width="358" border="1">
<tr>
<th colspan="5">Activities</th>
</tr>
<tr class="header">
<td width="104">Activity</td>
<td width="163">Rating</td>
<td width="69">Hours Per Week</td>
<td width="163">Weeks Per Year</td>
<td width="163">Average Hours Per Week</td>
</tr>
<tr>
<td class="title"><input type="text" value=""/></td>
<td><select name="rating">
<option value=""></option>
  <option value="High">High</option>
  <option value="Moderate">Moderate</option>
</select></td>
<td class="title"><input type="text" value=""/></td>
<td class="title"><input type="text" value=""/></td>
<td>&nbsp;</td>
</tr>
<tr>
<td class="title"><input type="text" value=""/></td>
<td><select name="rating">
<option value=""></option>
  <option value="High">High</option>
  <option value="Moderate">Moderate</option>
</select></td>
<td class="title"><input type="text" value=""/></td>
<td class="title"><input type="text" value=""/></td>
<td>&nbsp;</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td class="title">Total High</td>
<td class="title" id="totalHigh"></td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td class="title">Total Moderate</td>
<td class="title" id="totalModerate"></td>
</tr>
<tr>
<td colspan="5"><button class="copy"  value="Set Value">Submit</button></td>
</tr>
</table>

I need to perform a couple of calculations as follows:

  1. for each row I need to calculate the “Average Hours Per Week” which is simply the (Hours Per Week * Weeks Per Year)/52

  2. for each row the user can select either “High” or “Moderate” for the Rating. I need to then calculate the total of the “Average Hours Per Week” for all rows where Rating = “High” and all rows where Rating = “Moderate”.

I’ve spent the better part of today pulling out my last remaining hairs trying to get something working using jQuery which I’m a newbie with. I’ve setup a jsfiddle at:

http://jsfiddle.net/tZPDr/

which has a simplified version of the table. Would greatly appreciate any help about how to go about performing these 2 calculations dynamically as the user types.

Many thanks,
Steve

Answer by Starx

If you want to do this as user types, you need to bind onto keypress or keydown.

Example:

$('td.hours input').on('keypress', function() {
   //get  the values and calculate
});

Then choose you fields and perform the calculations. You can get the values like this

Example:

var hrs = $('td.hours input').val();

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!