我在哪里以及如何为rails 3.1选择标记onchange事件编写事件处理程序?

时间:2021-07-26 20:14:34

I am trying to do a very basic onChange event handler for a Rails 3.1 select tag. Most of the solutions I find are specific to ajax, but I am looking for something more simple, and what I have coded does not even seem to be recognized. In my view, I have the following:

我正在尝试为Rails 3.1选择标记执行一个非常基本的onChange事件处理程序。我发现的大多数解决方案都是针对ajax的,但我正在寻找更简单的东西,而我编码的内容似乎甚至都没有得到认可。在我看来,我有以下几点:

<h4><%= f.select :challenge_type, options_for_select(challenge_types, selected_type),
  :onchange => 'show_appropriate_challenge()' %></h4>

In my xxx.js.coffee file I have this (I tried many different alterations of this, none seem to make a difference):

在我的xxx.js.coffee文件中,我有这个(我尝试了很多不同的改动,似乎没有任何区别):

$('show_appropriate_challenge') ->
   alert('Hello from your onChange handler')

When I select an option from the drop down, nothing happens, and there are no messages in the console. Even if I change my select tag's onChange to something invalid (i.e. ...onchange => 'no_such_function()' ...), I still get no errors, so I suspect I am missing a configuration item or other item that hooks everything together.

当我从下拉列表中选择一个选项时,没有任何反应,并且控制台中没有消息。即使我将select标签的onChange改为无效的东西(即...... onchange =>'no_such_function()'...),我仍然没有错误,所以我怀疑我错过了一个配置项或其他挂钩一切的项目一起。

What other items might I need to add, or what changes to either code snippet might be needed?

我可能需要添加哪些其他项目,或者可能需要对任一代码段进行哪些更改?

Thank you for any help on this.

谢谢你对此有任何帮助。

1 个解决方案

#1


0  

Please, update your view to:

请将您的观点更新为:

<h4><%= f.select :challenge_type, options_for_select(challenge_types, selected_type),
  :id => 'challenge_selector' %></h4>

This will add an id with the name challenge_selector to your select tag. Now, you can bind an on change event to this id, using coffeescript, like this:

这会在您的select标记中添加名称为challenge_selector的id。现在,您可以使用coffeescript将on change事件绑定到此id,如下所示:

$('#challenge_selector').on 'change', ->
   alert('Hello from your onChange handler')

#1


0  

Please, update your view to:

请将您的观点更新为:

<h4><%= f.select :challenge_type, options_for_select(challenge_types, selected_type),
  :id => 'challenge_selector' %></h4>

This will add an id with the name challenge_selector to your select tag. Now, you can bind an on change event to this id, using coffeescript, like this:

这会在您的select标记中添加名称为challenge_selector的id。现在,您可以使用coffeescript将on change事件绑定到此id,如下所示:

$('#challenge_selector').on 'change', ->
   alert('Hello from your onChange handler')