How can I submit a form to RoR whenever the input text field changes?

I am using Ruby on Rails.

I want to create a filter field on the page so that whenever the value of the input field changes, I filter the list shown below through ajax. (Exaclty, like user search, works in Stackoverflow)

I currently run it using form_remote_tag containing text_field_tag ​​and submit_tag, and it filters my list when I click the submit button. I would like to remove the submit button and filter every time the value of the text input changes. How can I initiate a form submission every time the text in the input field changes?

I tried in my form

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

to receive the onchange event, but somehow this warning does not appear ...

+3
source share
2 answers

Use the register_field helper with a single input, for example below:

<%= 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 the parameter named "typed_filter", displays the results that will be displayed in the element with the identifiers "results" (probably a div).

+4
source

In general, for text inputs, you want to use onkeypress, onkeyup, onkeydown events, rather than onchange for this type of autocomplete. @Ricardo Acras' solution is much better than writing on your own, but I thought you might know that onchange doesn’t work because it doesn’t work until you go from text input (and the text has been changed).

, w3schools.com - . Javascript HTML DOM. .

+3

Source: https://habr.com/ru/post/1698707/


All Articles