[英]Rails 4: How to Disable Text Field Based on Checkbox Value Using JQuery in Rails
I have a check box and a text field in a form. 我在表单中有一个复选框和一个文本字段。 If the checkbox is checked, I want to disable the field (and if it's unchecked, I want it to be enabled). 如果选中此复选框,则我想禁用该字段(如果未选中,则希望启用该字段)。
I tried to write some jQuery based on the second answer for this question: jQuery - checkbox enable/disable 我尝试根据此问题的第二个答案编写一些jQuery: jQuery-启用/禁用复选框
However, the text field is (foo_price) is disabled when the page loads even though the field is unchecked. 但是,即使未选中该字段,在加载页面时也会禁用(foo_price)文本字段。 What am I doing wrong? 我究竟做错了什么?
I'm using the Simple Form gem : 我正在使用Simple Form gem :
<%= simple_form_for @foo do |f| %>
<%= f.input :free_flag, as: :boolean %>
<%= f.input :price %>
<%= f.button :submit %>
<% end %>
The form renders: 表单呈现:
<form>
<input class="boolean optional" type="checkbox" value="1" name="foo[free_flag]" id="foo_free_flag" />
<input class="numeric decimal optional" type="number" step="any" value="12.99" name="foo[price]" id="foo_price" />
</form>
My Coffeescript: 我的咖啡脚本:
enable_cb = ->
$('#foo_price').prop 'disabled', !@checked
return
$ ->
enable_cb()
$('#foo_free_flag').click enable_cb
return
The problem arise from the fact when you use enable_cb()
on DOM load directly the property checked
its refers to window object rather than checkbox element 问题来自以下事实:当您在DOM上直接使用enable_cb()
,直接checked
属性是指窗口对象,而不是复选框元素
I would recommend the usage of change
event instead of click
for checking the checked
property. 我建议使用change
事件,而不是click
以检查checked
属性。 You should use .trigger(event)
to programmatically execute the event handler. 您应该使用.trigger(event)
以编程方式执行事件处理程序。
enable_cb = ->
$('#foo_price').prop 'disabled', !@checked
return
$ ->
$('#foo_free_flag').change enable_cb
.trigger('change')
return
You can make use of javascript/jquery to do this, check this out this fiddle 您可以使用javascript / jquery来执行此操作,请查看此小提琴
<input type = "text" class="txt1"/>
<input type="radio" class="radio1"/>
$(function(){
$(".radio1").change(function(){
alert($(".radio1").prop("checked"));
if($(".radio1").prop("checked") == true){
$(".txt1").prop("disabled", true);
}else{
$(".txt1").prop("disabled", false);
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.