views:

540

answers:

2

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...

+4  A: 

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).

Ricardo Acras
great, it works perfectly! thank you
balint.miklos
+3  A: 

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.

tvanfosson