Search code examples
javascriptruby-on-railsrjs

How to create an OnChange "totaling" function from an unknown number of text fields


I'm having trouble figuring out how to do a simple Javascript task on fields in a table created with Rails 3.

My table has characteristic rows that the user adds using a form below (which updates the database and reloads the table partial).

The number of columns in the table is based on the number of attributes submitted in a different form. No matter how many columns are in a row, there is also a Total column after them. Each cell in the table has a text_field input, with an ID that is based on the row object id and the column object id.

What I'm trying to do is create an OnChange event for each of those cells, so that when a field value changes, the Total column gets updated with the total value in the text_field inputs of all cells in that row.

I don't know how to pass the Rails objects to Javascript (so I can cycle through the IDs), I can't figure out how to get the DOM element names and values if I use an action in the controller, and I don't know how to use RJS to do this either. Can anyone offer any help on how to do this? Thank you!

Sarah


Solution

  • If you use jQuery, you can set a class on the textboxes and listen to the change event on it.

    example:

    <input type="text" id="WhateverXXX" class="MyValue" />
    
    <script type="text/javascript">
        $(function(e) {
            $('.MyValue').change(function(e) {
                // update the total
            });
        });
    </script>