views:

62

answers:

1

Basically I'm trying to create to use a table as a look-up table. Normally, I would do this server side, but in this case I just have an html table and the table is going to be inputted by the client.

Basically, when filling out a form they give me two values which are in columns A & B. Then the form needs to do a calculation using the corresponding value in Column C. Column A is repeated multiple times, rather then entering it multiple times, the rowspan attribute is used, which seems to be really complicating this, but it would be a big deal to change (it might be possible, but I'd rather avoid).

A simplified version:

<table>
  <thead>
    <tr><th>Column A</th><th>Column B</th><th>Column C</th></tr>
  </thead>
  <tbody>
    <tr>
      <td rowspan="3">val1</td>
      <td>1</td>
      <td>2</td>
    </tr>
    <tr>
      <td>2</td>
      <td>2</td>
    </tr>
    <tr>
      <td>2</td>
      <td>3</td>     
    </tr>
    <tr>
      <td rowspan="2">val2</td>
      <td>4</td>
      <td>5</td>
    </tr>
    <tr>
      <td>10</td>
      <td>15</td>
    </tr>
  </tbody>
</table>

So if they input: val1 and 1 -> 2 val2 and 4 -> 5 val2 and 10 -> 15

The one idea I have is to first parse the table into a nested array and then use it. It appears to work, but I wanted to get others opinion on the best way to handle this. If I could just query/filter based on the DOM it seems like it would use less memory, but again the rowspan attribute seems to make those solutions ugly.

Thanks!

Edit: correct having the second rowspan attribute on the tr tag instead of the td tags Edit: tried clarifying via the example section that you could potentially look up any row

A: 

I think the best way (other than working w/ the form data server side) would be to use jQuery to work with the form data directly before it's submitted rather than working with the HTML result.

But if you have no control over that, this will bring the first row for each "val#" rowspan's "C" column value into an object keyed by each "val#" string where you can work with it (via a for in loop for example). You should add an "id" attribute (eg: id="myTable") to your table tag because that will optimize the jQuery selector.


$(window).ready(function() {
  var vals = {}, $table = $('#myTable');

  $table.find('td[rowspan]').each(function(i,e) {
    $(e).siblings().each(function(j,s) {
      var html = e.innerHTML, key = (html.match(/^[a-z0-9]+$/)) ? html : i.toString();

      vals[key] = parseInt($(s).html(), 10);
    });
  });

  for(var val in vals) {
    if(!vals[val]) continue;

    vals[val] = vals[val] + 20;

    alert(vals[val]); // alerts 22, then 25
  }
});
taber