我有一个带有单选按钮的 form_for,我想在单选按钮更改时调用 JavaScript 函数。
单选按钮适用于章节的“类型”字段, bool 类型。
<%= 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 %>
<小时/>
另一种方法是使用数据标签定义行为,然后用 javascript 绑定(bind)它(引用: 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();
}
});
});
关于javascript - rails : Calling JS function on form_for radio buttons,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24580851/