Javascript 选中复选框时禁用表单元素
在我的rails应用程序中,我的表单中有这两个字段,我尝试在选中该复选框时禁用end_date字段,因此我有下面的jQuery代码Javascript 选中复选框时禁用表单元素,javascript,jquery,ruby-on-rails,ruby-on-rails-4,Javascript,Jquery,Ruby On Rails,Ruby On Rails 4,在我的rails应用程序中,我的表单中有这两个字段,我尝试在选中该复选框时禁用end_date字段,因此我有下面的jQuery代码 <div class="form-profile end-date"> <%= f.label :experience_end, class: "profile_label" %><br/> <%= f.date_select :experience_end, {start_year: 1945, discard_d
<div class="form-profile end-date">
<%= f.label :experience_end, class: "profile_label" %><br/>
<%= f.date_select :experience_end, {start_year: 1945, discard_day: true, order: [ :day, :month, :year ]}, :html=> {class: 'date-select'} %>
</div>
<div class="form-checkbox">
<%= f.check_box :experience_current,class: 'is_current', id: "checkbox_id" %>
I currently work here
</div>
这项工作很好,除了当我提交表单并尝试再次访问它以编辑表单时,在这种情况下,我发现复选框已选中,但表单未被禁用,因此我想知道如何解决此问题。您需要检查是否禁用document ready上的元素 试试这个:
function disableEndDate() {
if($('#checkbox_id').prop("checked")) {
$('.end-date select').prop(
'disabled', true
);
$('.end-date select').css(
"background-color", "#D9D8DD"
);
}
function enableEndDate() {
$('.end-date select').prop(
'disabled', false
);
$('.end-date select').css(
"background-color", "white"
);
}
$(document).ready(function() {
disableEndDate();
$("input[class='is_current']").click(function() {
disableEndDate();
} else {
enableEndDate();
}
});
});
您应该通过将逻辑聚合到函数中来改进它。如果重新加载页面,这可能会起作用:
if ($('input.is_curent').prop('checked')) {
$('.end-date select').prop(
'disabled', false
);
$('.end-date select').css(
"background-color", "white"
);
}
上面的代码只是检查复选框是否被选中,并根据复选框的状态禁用表单元素。您只是在复选框的
单击上禁用表单字段。因此,当页面(重新)加载时,不会触发任何单击事件,因此不会执行任何逻辑。一种可能的解决方法是将逻辑抽象到函数中,该函数在页面加载和单击复选框的时调用
function disableStuff() {
// Perform disable logic
}
$(document).ready(function() {
disableStuff();
$('.selector').click(function() {
disableStuff();
});
});
尝试添加。最后单击()。它将在init.where上执行您的click处理程序来添加click()$(“input[class='is_current'])代码>此解决方案在每次重新加载页面时取消选中复选框
function disableStuff() {
// Perform disable logic
}
$(document).ready(function() {
disableStuff();
$('.selector').click(function() {
disableStuff();
});
});