如何仅选择一个复选框

时间:2019-06-18 13:32:57

标签: jquery html

我在span元素内自定义创建了Checkbox。单击范围时,我抓住最近的复选框,并选中其属性。但是如何只实现一个复选框被选中?

var tmp = '<div class="nB vCenter mr10">' +
        '<span class="B w15 h15 rad5 whiteBkg blackBrdr " data-offstate="blackBrdr" data-onstate="whiteBkg blackBrdr">' +
        '<input type="checkbox"  class="i_chk hide"  name="teamFolder" value=""/></span>' +
        '</div>' +
        '<div class="nB vCenter">' +
        '<label class="nB w160p">Team Folder</label>' +
        '</div>'  +
        '<div class="mt15">' +
        '<div class="nB vCenter mr10">' +
        '<span class="B w15 h15 rad5 whiteBkg blackBrdr " data-offstate="blackBrdr" data-onstate="whiteBkg blackBrdr">' +
        '<input type="checkbox" class="i_chk hide" name="teamFolder" value=""/></span>' +
        '</div>' +
        '<div class="nB vCenter">' +
        '<label class="nB w160p">Personal Folder</label>' +
        '</div>' ;

// this is the code for checkbox generation
    $(document).on('click', 'span', function () {
        var chk = $(this).find('.i_chk');
        if (chk.prop('checked')) {  
            chk.prop('checked', false);
            $(this).removeClass('greenTick');        
        } else if (chk.prop('checked') == false) {
            chk.prop('checked', true);
            $(this).addClass('greenTick'); 
        }
}

我试图获取所有复选框,并将未选中的复选框设为false

1 个答案:

答案 0 :(得分:0)

尝试一下:

/*   jQuery   */
add_html_to_dom(); //Demo only - injects the HTML in var "tmp" onto page

$(document).on('click', '.i_chk', function () {
   $('.i_chk').prop('checked', false); //uncheck ALL checkboxes
   $(this).prop('checked', true); //re-check THIS checkbox
});

function add_html_to_dom(){
   var tmp = '<div class="nB vCenter mr10">' +
        '<span class="B w15 h15 rad5 whiteBkg blackBrdr " data-offstate="blackBrdr" data-onstate="whiteBkg blackBrdr">' +
        '<input type="checkbox"  class="i_chk hide"  name="teamFolder" value=""/></span>' +
        '</div>' +
        '<div class="nB vCenter">' +
        '<label class="nB w160p">Team Folder</label>' +
        '</div>'  +
        '<div class="mt15">' +
        '<div class="nB vCenter mr10">' +
        '<span class="B w15 h15 rad5 whiteBkg blackBrdr " data-offstate="blackBrdr" data-onstate="whiteBkg blackBrdr">' +
        '<input type="checkbox" class="i_chk hide" name="teamFolder" value=""/></span>' +
        '</div>' +
        '<div class="nB vCenter">' +
        '<label class="nB w160p">Personal Folder</label>' +
        '</div>' ;
   $('body').append(tmp);
}
/*   CSS   */
.nB{display:inline-block;}
<!-- HTML -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>