Ellen Spertus
Ellen Spertus

Reputation: 6805

How to run javascript code in Rails when form submitted via text field?

I define a table of editable text fields in HAML like this:

%table
  %tbody
    %tr
      %td
        -hints.each do |hint|
          =form_for(level_source_hint, :remote => true) do |f1|
            =text_field_tag 'message' + hint.id.to_s, 
               level_source_hint.hint, class: 'input-xxlarge'
      %td{:id => 'sibling' + hint.id.to_s} ...

Note that there is not a submit button. If someone edits the text field and presses return, an update request is sent, which works.

When the user submits the form, I would like to do something in javascript to the sibling node (in the second %td). I've tried adding an :onchange attribute to the form_for tag, but it doesn't show up in the generated html.

While I might be able to bind functions to each of the different forms, doing so would be ugly because I would need to create a different function for each row (the number of which is not known until runtime), and each function would have to hardcode which row it came from (e.g., its hint.id).

Do I really need to create and bind one function for each form, or is there a more elegant solution?

I am using Rails 4.0.3 with jquery-rails 3.1.10 and jquery-ui-rails 4.2.0.

Upvotes: 0

Views: 210

Answers (1)

CWitty
CWitty

Reputation: 4526

You can actually bind to their parent element and then check which element it was when the event bubbles up to the handler. Something like $('#parent_id').on('change', '.field-class', function(){//your code here dealing with submit});

Upvotes: 1

Related Questions