[英]How can I submit a form in RoR whenever an input textfield changes?
I am using Ruby on Rails. 我正在使用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. 我想在页面上创建一个过滤器字段,这样每当输入字段的值发生变化时,我都会通过ajax过滤下面显示的列表。 (Exaclty like the Users search works in Stackoverflow) (例如用户搜索在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. 现在,我使用包含text_field_tag和submit_tag的form_remote_tag运行它,当我按下提交按钮时它会过滤我的列表。 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... 只是为了得到onchange事件,但不知何故甚至没有这个警报出现......
Use observe_field helper with a single input, like the code bellow: 将observe_field助手与单个输入一起使用,如下面的代码:
<%= 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). 然后编写一个控制器,给定一个名为'typed_filter'的参数,渲染结果,它将显示在id为'results'的元素中(可能是div)。
In general for text inputs you want to use onkeypress, onkeyup, onkeydown events, not onchange for this type of autocomplete. 通常,对于文本输入,您希望使用onkeypress,onkeyup,onkeydown事件,而不是onchange用于此类自动完成。 @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). @Ricardo Acras解决方案比编写自己的解决方案要好得多,但我想你可能想知道onchange不起作用,因为它不会触发,直到你导出文本输入(并且文本已被更改)。
I find that w3schools.com is a great resource for this kind of info. 我发现w3schools.com是这类信息的绝佳资源。 Here is there page on Javascript HTML DOM. 这里有关于Javascript HTML DOM的页面。 And here is the event reference. 这是事件参考。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.