Rails:在form_for单选按钮上调用JS函数

Rails: Calling JS function on form_for radio buttons

本文关键字:调用 JS 函数 单选按钮 for form Rails      更新时间:2023-09-26

我有一个单选按钮的form_for,当单选按钮被改变时,我想调用一个javascript函数。

单选按钮用于Chapter的字段type,类型为boolean。

<%= form_for([book.category, book, chapter], remote: true ) do |f| %>
    <%= f.radio_button :type, true, onKeyUp: "alert('hi')", checked: 'checked' %> 
    <%= f.label :type, 'Link' %>
    <%= f.radio_button :type, false, onKeyUp: "alert('hi')" %> 
    <%= f.label :type, 'Text' %>
<% end %>

我也试过onchange和onclick。我试着在选项之前添加{},我从Rails得到一个错误,有太多的参数。

最后我想调用一个隐藏/显示其他文本字段的函数,但我甚至不能得到警报执行!

我确信这是非常简单的事情,但是我已经在互联网上搜索这个问题的答案太久了。谢谢你的帮助!

这段代码实际上与onclick事件一起工作,在浏览器中使用开发人员扩展(如Firebug)检查生成的HTML代码,以确保属性设置正确。

<%= form_for([book.category, book, chapter], remote: true ) do |f| %>
    <%= f.radio_button :type, true, checked: 'checked', onClick: "alert('hi TRUE!');" %> 
    <%= f.label :type, 'Link' %>
    <%= f.radio_button :type, false, onClick: "alert('hi False!');" %> 
    <%= f.label :type, 'Text' %>
<% end %>

另一种方法是使用data标签定义行为,然后将其与javascript绑定(参考:http://blog.bigbinary.com/2012/10/10/data-behavior.html):

)
<%= form_for([book.category, book, chapter], remote: true ) do |f| %>
    <%= f.radio_button :type, true, checked: 'checked', data: {behavior: "clickable"} %> 
    <%= f.label :type, 'Link' %>
    <%= f.radio_button :type, false, data: {behavior: "clickable" } %> 
    <%= f.label :type, 'Text' %>
<% end %>
JavaScript:

$(document).ready(function() {    
  $('input[type="radio"][data-behavior="clickable"]').click(function(evt) {
    alert("you chose the option: " + $(this).val());
  });
});

让我们将其扩展到隐藏/显示其他内容的场景:

视图ERB:

<%= form_for([book.category, book, chapter], remote: true ) do |f| %>
    <%= f.radio_button :type, true, checked: 'checked', data: {behavior: "toggle-products"} %> 
    <%= f.label :type, 'Link' %>
    <%= f.radio_button :type, false, data: {behavior: "toggle-products" } %> 
    <%= f.label :type, 'Text' %>
<% end %>
JavaScript:

$(document).ready(function() {
  $('input[type="radio"][data-behavior="toggle-products"]').click(function(evt) {
    if($(this).val() == "true") { 
      $('.products').show();
    } else {
      $('.products').hide();
    }
  });
});