1

See the site and code here: http://jonathonmoore.com/sandbox/single.html

I'm creating a site that essentially gives users a bi-weekly, monthly, and annual view of their financials. I have a large table with four columns:

enter image description here

Right now, I'm kind of brute-forcing the values in the table by having giving each cell a unique ID (#bwSalary, #monSalary, #annSalary, etc...), doing the math, and replacing the text.

This is messy. There's another portion of the page that allows users to add and delete rows to a table, and enter in their various expenses. I can't be generating unique IDs for each one. There has to be a better way.

So my question is whether or not there is a way, using jQuery, to assign each column an equation - similar to what you can do in Excel. What I'm envisioning is calculating the annual contribution for each row (probably using unique IDs), and then jQuery will go through each row and populate the bi-weekly and monthly rows by just taking the value in the annual column cell and dividing it by 12 or 26. Make sense?

I know there's a way to do it, I just don't know jQuery well enough to know how to find the right cells that I need.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Jon
  • 3,154
  • 13
  • 53
  • 96

1 Answers1

1

One easy way to implement your second table uses raw JQuery and avoids hardcoded IDs by just programmatically finding the other input boxes in the same row. Here's some Coffeescript to illustrate:

# whenever the user finishes entering a value and clicks away
$('table input').on 'blur', ->
  # find all three input boxes in this row
  [biweekly, monthly, annual] = $(this).parents('tr').find('input')
  # update the first two in terms of the third
  $(biweekly).val($(annual).val() / 52 * 2)
  $(monthly).val($(annual).val() / 12)

If your application is to become more complex (or if you're just interested), you may want to look into reactive programming systems, such as tangle, angular, ember, etc. Much like Excel, they'll let you declare the value of something to be some expression (i.e. formula) of another thing, and the system will ensure that whenever one thing changes, all dependent bindings are also updated.

Yang
  • 16,037
  • 15
  • 100
  • 142