簡體   English   中英

更有效的方法來使用document.getElementById復選框?

[英]More efficient way to use document.getElementById for checkboxes?

這部分代碼使用jQuery隱藏/顯示表單字段。 隱藏它們時,這些字段的值將設置為空。 對於具有唯一ID的輸入字段,這很容易。 我遇到了復選框的問題。 下面的代碼適用於三個復選框。 但我必須使用相同的技術來處理一組26個復選框。 我怎樣才能更有效地做到這一點?

$(".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>

使用類,因為許多元素可以共享一個類。 因此,您只需取消選中某個類的所有復選框:

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

當然,使用jquery選擇器的驚人力量!

$('li.transfer_details input[type=checkbox]').prop("checked", false);

后代選擇器 - http://api.jquery.com/descendant-selector/

設置選中的屬性 - http://api.jquery.com/prop/

一種方法是將子選擇器與復選框選擇器結合使用,並使用jQuery中的每個函數進行迭代,以完成您正在尋找的內容。

請記住,這是未經測試的,所以它可能會引發錯誤,我相信你會解決這個問題。 在你的上滑效果下,你需要以下內容:

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

希望這有助於編碼!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM