【问题标题】:How do you add onchange action to collection_select?如何将 onchange 操作添加到 collection_select?
【发布时间】:2016-02-29 18:42:50
【问题描述】:

我的导轨中有以下选择下拉菜单。我正在遵循 API 中的语法(http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-collection_select):

collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})

<%= collection_select(:sources, :source_id, Source.all, :id, :name, :include_blank => "Please select a source...", html_options = {:onchange => "updateTextArea()"} ) %>

function updateTextArea(){
 alert('source changed')
}

当我不包含 html_options 时,我可以让下拉菜单很好地显示来自数据库的值。但是,我一直在尝试执行 onchange 操作。

【问题讨论】:

    标签: javascript ruby-on-rails


    【解决方案1】:

    我认为 options 需要放在一个散列中(你目前有 include_blank 的部分)。尝试更改此设置

    <%= collection_select(:sources, :source_id, Source.all, :id, :name, :include_blank => "Please select a source...", html_options = {:onchange => "updateTextArea()"} ) %>
    

    到这里

    <%= collection_select(:sources, :source_id, Source.all, :id, :name, options = {include_blank: "Please select a source..."}, html_options = {:onchange => "updateTextArea()"} ) %>
    

    【讨论】:

    • 这让我通过了语法异常,但是它没有给我一个警报对话框,所以我不确定为什么当我更改下拉值时没有触发该函数。
    • 我的错误,我的
    【解决方案2】:

    我相信代替 options =html_options = 您需要传递实际的哈希本身(就像您实际上对 include_blank =&gt; true 所做的那样)。我只会用花括号明确标记这些哈希以将它们分开:

    <%= collection_select(:sources, :source_id, Source.all, :id, :name, { :include_blank => "Please select a source..."}, {:onchange => "updateTextArea()"} ) %>
    

    希望这会有所帮助。

    编辑:

    我忘了补充一点,如果updateTextArea() JS 函数没有绑定到窗口,那么在拾取它时可能会出现问题(我过去也遇到过类似的问题)。为了安全起见,我也会这样做(如果您不使用 CoffeScript):

    window.updateTextArea = function() { /* Your code */ }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-09
      • 1970-01-01
      • 1970-01-01
      • 2016-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多