簡體   English   中英

使用jQuery檢查相應的復選框

[英]using jquery check the corresponding checkbox

jQuery問題的新手...

使用jQuery,取決於單擊的單選按鈕,我希望jQuery自動“選中”相應的復選框。

<input type="radio" value="#ID#" name="#ID#1" 
       onclick="return tickSession(this);"/>
<input type="checkbox" value="#ID#" id="#ID#" 
       name="sessionsThatNeedBookingOnto" class="#ID#1"/>

<input type="radio" value="#ID#" name="#ID#1" 
       onclick="return tickSession(this);"/>
<input type="checkbox" value="#ID#" id="#ID#" 
       name="sessionsThatNeedBookingOnto" class="#ID#1"/>

<input type="radio" value="#ID#" name="#ID#2" 
       onclick="return tickSession(this);"/>
<input type="checkbox" value="#ID#" id="#ID#" 
       name="sessionsThatNeedBookingOnto" class="#ID#2"/>

這是我嘗試過的,但我的理解還差一點……

<script>
    function tickSession(elementHere){
            alert($(elementHere).val());
            $(elementHere).attr('id').attr("checked", "true");
            $($(elementHere).val()).attr('checked','checked')

    }
  </script>
<script>

$(document).ready(function(){

$('input:radio').click(function(){

      $(this).next('checkbox').attr('checked',true);
});

});

</script>

讓我們重新制作您的復選框/收音機:

<input type="radio" value="#ID#" name="rd1" class='rd-session-control'/>
<input type="checkbox" value="#ID#" id="for-rd1" 
    name="sessionsThatNeedBookingOnto" class="#ID#1"/>

現在:

$(function() {
    $('.rd-session-control').click(function() {
        var checkbox = $('#for-' + $(this).attr('id'));
        if (checkbox.is(':checked'))
            checkbox.removeAttr('checked');
        else
            checkbox.attr('checked', 'checked');
    });
});

這是什么:

  1. 允許您使用類rd-session-control一次設置所有收音機的點擊處理程序。
  2. 復選框的ID屬性是理智的,相對於控制它們的無線電而言很容易計算。
  3. 使用:checked選擇器測試復選框是否處於活動狀態。

暫無
暫無

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

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