[英]Disable form element when checkbox is checked
在我的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_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>
jQuery代碼
$(document).ready(function(){
$("input[class='is_current']").click(function() {
if($('#checkbox_id').prop("checked")) {
$('.end-date select').prop(
'disabled', true
);
$('.end-date select').css(
"background-color", "#D9D8DD"
);
} else {
$('.end-date select').prop(
'disabled', false
);
$('.end-date select').css(
"background-color", "white"
);
}
});
});
除我提交表單並嘗試再次訪問該表單以進行編輯外,此工作一切正常,在這種情況下,我發現該復選框已選中,但未禁用該表單,所以我想知道如何解決此問題異味
您需要檢查禁用文檔准備就緒的元素。
嘗試這個:
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"
);
}
上面的代碼只是檢查復選框是否被選中,並根據復選框的狀態禁用表單元素。
您僅在click
復選框時禁用表單字段。 因此,在頁面(重新)加載時,沒有觸發點擊事件,因此不執行任何邏輯。 解決此問題的一種可能方法是將邏輯抽象到一個函數中,在頁面加載和click
復選框時都將其稱為。
function disableStuff() {
// Perform disable logic
}
$(document).ready(function() {
disableStuff();
$('.selector').click(function() {
disableStuff();
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.