Sunday, February 13, 2011

How can I submit a form in RoR whenever an input textfield changes?

I am using Ruby on Rails.

I want to create a filter field on a page such that whenever the input field's value changes I filter a list shown below via ajax. (Exaclty like the Users search works in Stackoverflow)

For now, I made it run with a form_remote_tag containing a text_field_tag and a submit_tag, and it filters my list when I push the submit button. I would like to remove the submit button and execute the filtering every time the value of the text input changes. How can I trigger a form submit every time the text in an input field changes?

I tried inside my form

<%= text_field_tag (:filter), "" , :onchange => "alert ('This is a Javascript Alert')" %>

just to get the onchange event, but somehow not even this alert appears...

  • Use observe_field helper with a single input, like the code bellow:

    <%= text_field_tag 'filter' %>
    <%= observe_field 'filter', 
        :url => {:controller => 'your_controller', :action => 'filter'},
        :frequency => 1.2,
        :update => 'results',
        :with => "'typed_filter=' + $('filter').value" %>
    

    And then just write a controller that, given a param named 'typed_filter', renders the results, wich will be shown in the element with id 'results' (probably a div).

    balint.miklos : great, it works perfectly! thank you
  • In general for text inputs you want to use onkeypress, onkeyup, onkeydown events, not onchange for this type of autocomplete. @Ricardo Acras solution is far better than writing your own, but I thought you might want to know that onchange doesn't work because it doesn't fire until you navigate out of the text input (and the text has been changed).

    I find that w3schools.com is a great resource for this kind of info. Here is there page on Javascript HTML DOM. And here is the event reference.

    From tvanfosson

0 comments:

Post a Comment