2013-12-18 63 views
1

這段代碼使用jQuery來隱藏/顯示錶單域。當它們被隱藏時,這些字段的值被設置爲空。這對於具有唯一ID的輸入字段很容易。我用複選框遇到麻煩。下面的代碼適用於三個複選框。但是我必須使用相同的技巧來設置26個複選框。我怎樣才能更有效地做到這一點?更有效的方式來使用document.getElementById複選框?

$(".transfer").click(function(){ 
    if ($('input[name=transfer_position]:checked').val() == "yes") { 
     //Slide Down Effect 
     $(".transfer_details").slideDown("slow"); 
     document.getElementById('transfer_interest').focus(); 
    } else { 
     //Slide Up Effect 
     $(".transfer_details").slideUp("slow"); 
     document.getElementById('transfer_interest').value = ""; 
     document.getElementById('select_positions_0').checked = false; 
     document.getElementById('select_positions_1').checked = false; 
     document.getElementById('select_positions_2').checked = false; 
    } 
}); 

<li> 
     <label> 
     <input type="radio" name="transfer_position" class="transfer" value="yes" id="transfer_position_0" /> 
     Yes</label> 
     <label> 
     <input type="radio" name="transfer_position" class="transfer" value="no" id="transfer_position_1" /> 
     No</label> 
    </li> 
    <li class="transfer_details"> 
    <label for="transfer_interest">Why are you interested in transferring to your selected SL positions and what would you bring to that position(s) and team(s)?</label> 
    <textarea name="transfer_interest" id="transfer_interest" cols="80" rows="6"> </textarea> 
    </li> 
    <li class="transfer_details"> 
     <label> 
     <input type="checkbox" name="select_positions[]" class="select_positons" value="Resident Advisor" id="select_positions_0" /> 
     Resident Advisor</label> 
     <label> 
     <input type="checkbox" name="select_positions[]" class="select_positons" value="Programming Assistant" id="select_positions_1" /> 
     Programming Assistant</label> 
     <label> 
     <input type="checkbox" name="select_positions[]" class="select_positons" value="Social Justice Advocate " id="select_positions_2" /> 
     Social Justice Advocate </label> 
    </li> 
+0

他們都有相同的類。你有沒有考慮通過課堂選擇他們?或按名稱?或由共同的父母? –

回答

3

使用類,因爲很多元素可以共享一個類。所以你只需取消選中某個類的所有複選框:

$('.select_positions').attr('checked', false); 
+0

添加註釋以確保用戶包含jQuery庫。 –

+1

@KyleB。鑑於問題被標記爲jQuery並使用jQuery風格的代碼,我認爲這是顯而易見的:) –

+0

顯然我需要我的眼鏡,因爲我錯過了。好點子。 –

0

一種方法是將與複選框選擇結合使用子選擇器,並使用每個功能的jQuery遍歷去完成你正在尋找的東西。

請記住,這是未經測試的,所以它可能會引發錯誤,我相信你會解決這個問題。 的下方向上滑動效果,你想要的東西類似如下:

$('.transfer_details > input:checkbox').each(function() { 
(this).checked = false; 
}); 

希望這有助於和編碼快樂!

相關問題