2017-07-01 68 views
1

在HTML中,每場都有一個複選框旁邊的文本輸入,就像這樣:jQuery的:切換基於同級複選框禁用狀態,集體

<div class="field"> 
    <input type="checkbox" id="checkbox1" /> 
    <input type="text" id="textbox1" /> 
</div> 
<div class="field"> 
    <input type="checkbox" id="checkbox2" /> 
    <input type="text" id="textbox2" /> 
</div> 

使用jQuery's Attribute Starts With Selectors,很容易扎click事件上與其兄弟文本框的禁用狀態的每個複選框 - 這已經工作得很好:

$("input[id^='checkbox']").click(function() { 
    $(this).siblings().prop("disabled", !this.checked); 
}); 

我無法弄清楚什麼是相似的簡要說明,我可以運行一個時間(從另一個事件),將切換所有這些文本框基於其關聯的當前選中狀態特德複選框。以下是大致什麼我以爲這是應該的,但它只是切換所有的人,而不是每個單獨酌情 - 即它不工作:

$("input[id^='textbox']").prop("disabled", $(this).prev().is(':checked')); 

我也試圖與一個變化處理程序,但它當複選框本身重新啓用時不會觸發。

對我有何建議?

+0

更新我的答案。 –

回答

1

如果我已經正確理解你,你想啓用文本輸入,如果相應的複選框檢查。建議的方法:

$('input[type="checkbox"]').on('change', function() { 
 
    $(this).next().prop('disabled', !this.checked); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="field"> 
 
    <input type="checkbox" id="checkbox1" /> 
 
    <input type="text" disabled id="textbox1" /> 
 
</div> 
 
<div class="field"> 
 
    <input type="checkbox" id="checkbox2" /> 
 
    <input type="text" disabled id="textbox2" /> 
 
</div>

+0

啊,好點 - 更改處理程序是保持這些同步的好方法。我之所以沒有在我的問題中解釋(因爲我試圖簡化它)是因爲我希望在其他更改之後啓用啓用/禁用 - 具體而言,可以禁用並重新整理表單的整個部分,啓用。更改處理程序不會捕獲啓用/禁用更改:( – ewall

+0

@ewall您希望一次禁用/啓用所有文本輸入嗎? –

+0

我有其他事件可禁用或啓用表單的整個部分。 ,我需要它根據它們的複選框來觸發文本字段的啓用/禁用。當複選框被啓用時,更改處理程序不會觸發 – ewall

0

change活動的其他,你可以使用click事件除了相關sibling查詢到明年訪問文本框的複選框。而在您的評論的更新,你可以使用一個fieldset元素來實現你想要的:

$(".field > :checkbox").on("click", function(){ 
 
if($(this).is(":checked")){ 
 
    $(this).siblings("fieldset").removeAttr("disabled"); 
 
}else{ 
 
    $(this).siblings("fieldset").attr("disabled","disabled"); 
 
} 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="field"> 
 
    <input type="checkbox" id="checkbox1" /> 
 
    <fieldset disabled="disabled" > 
 
     <input type="text" id="textbox1-1" /> 
 
     <input type="text" id="textbox1-2" /> 
 
     <textarea id="textarea-1"></textarea> 
 
     <input type="checkbox">Test 1 
 
    </fieldset> 
 
</div> 
 
<div class="field"> 
 
    <input type="checkbox" id="checkbox2" /> 
 
    <fieldset disabled="disabled" > 
 
     <input type="text" id="textbox2-1" /> 
 
     <input type="text" id="textbox2-2" /> 
 
     <textarea id="textarea-2"></textarea> 
 
     <input type="checkbox">Test 2 
 
    </fieldset>  
 
</div>

+0

是的。可悲的是,我沒有很好地解釋爲什麼我要找一個一次性的命令,我可以根據它們的複選框的狀態啓用/禁用所有的字段。每次點擊或更改我可以做的事件。 – ewall