확인란 켜기 / 끄기


397

나는 다음을 가지고있다 :

$(document).ready(function()
{
    $("#select-all-teammembers").click(function() {
        $("input[name=recipients\\[\\]]").attr('checked', true);
    });                 
});

id="select-all-teammembers"클릭하면 체크 표시와 체크 해제 사이를 전환 하고 싶습니다 . 아이디어? 수십 줄의 코드가 아닙니까?

답변:


723

당신은 쓸 수 있습니다:

$(document).ready(function() {
    $("#select-all-teammembers").click(function() {
        var checkBoxes = $("input[name=recipients\\[\\]]");
        checkBoxes.prop("checked", !checkBoxes.prop("checked"));
    });                 
});

jQuery 1.6 이전 에는 prop ()이 아닌 attr () 만 있었을 때 다음 과 같이 작성했습니다.

checkBoxes.attr("checked", !checkBoxes.attr("checked"));

그러나 "부울"HTML 속성에 적용 할 prop()때보 attr()다 시맨틱이 우수 하므로 일반적으로이 상황에서 선호됩니다.


4
이것은 첫 번째 상태를 기반으로 엉 키게 될 수 있습니다 (따라서 사용자가 첫 번째 상태를 확인한 다음 토글을 사용하면 동기화되지 않습니다). $ ( "input [name = recipients \ [\]]"). prop ( "checked", $ (this) .prop ( " 확인 됨 "));
— CookiesForDevo

6
'prop'를 사용하면 Zepto에서도 작동합니다. 그렇지 않으면 확인란을 선택하지만 선택 해제하지는 않습니다.
— SimplGy

1
"attr"대신 "prop"가 트릭을 수행했습니다. "attr"을 사용하면 잠시 동안 전환 된 다음 중지되고 "prop"를 사용하여 예상대로 전환됩니다. 업데이트시 +1
— TechNyquist

11
$('input[type=checkbox]').trigger('click');아래 @ 2astalavista에 의해 언급 된 것은 간결하고 "변경"이벤트를 유발합니다.
— 여기

1
@CookiesForDevo의 답변을 지원하도록 답변을 편집 할 수 있습니까?
— acquayefrank

213
//this toggles the checkbox, and fires its event if it has    

$('input[type=checkbox]').trigger('click'); 
//or
$('input[type=checkbox]').click(); 

크롬 29에서는 작동하지만 FF 17.0.7에서는 작동하지 않습니다. 누군가 확인할 수 있습니까?
— Griddo

나는 오랫동안 재산을 바꾸는 길을 가고 있었다. 나에게 이것은 확인란 요소를 확인하고 선택 해제하기위한 훌륭하고 유연한 접근 방식입니다.
— Isioma Nnodum

원하지 않는 이벤트가 트리거됩니다.
— Jehong Ahn

확인란의 경우 일반적으로 라벨을 클릭하여 변경할 수 있으므로 '변경'이벤트를 시작하는 것이 좋습니다.
— 피터 렌조

61

나는 이것이 오래되었다는 것을 알고 있지만 그 토글 에서 약간 모호한 질문은 각 확인란이 상태를 토글해야한다는 것을 의미 할 수 있습니다. 3을 체크하고 2를 체크하지 않으면, 토글하면 처음 3을 체크하지 않고 마지막 2를 체크합니다.

이를 위해 각 확인란의 상태를 전환하지 않고 모든 확인란을 동일한 상태로 만드는 솔루션은 작동하지 않습니다. $(':checkbox').prop('checked')많은 확인란을 수행하면 모든 .checked이진 속성 간에 논리 AND가 반환 됩니다. 즉, 속성 중 하나를 선택하지 않으면 반환 값은 false입니다.

.each()각 확인란 상태를 모두 동일하게 만들지 않고 실제로 각 상태를 토글하려는 경우 사용해야 합니다. 예 :

   $(':checkbox').each(function () { this.checked = !this.checked; });

속성이 모든 브라우저에 존재 $(this)하므로 핸들러 내부에 필요하지 않습니다 .checked.


5
예, 이것은 모든 확인란의 상태를 토글하는 정답입니다!
— Sydwell

1
확인란이 많은 경우 jQuery로 클릭을 트리거하는 것보다 훨씬 빠릅니다.
— 제레미 쿡

16

여기 또 다른 방법이 있습니다.

$(document).ready(function(){   
    $('#checkp').toggle(
        function () { 
            $('.check').attr('Checked','Checked'); 
        },
        function () { 
            $('.check').removeAttr('Checked'); 
        }
    );
});

9
그것은 토글되지 않습니다.
— AgentFire

2
@kst-이것은 더 나은 방법입니다 $ ( 'input [name = recipients \ [\]]'). toggle (this.checked); 수업은 잊어 버리세요.
— Davis

11

클릭을 발생시키는 것이 더 간단하다고 생각합니다.

$("#select-all-teammembers").click(function() {
    $("input[name=recipients\\[\\]]").trigger('click');
});                 

9

내가 생각할 수있는 가장 좋은 방법.

$('#selectAll').change(function () {
    $('.reportCheckbox').prop('checked', this.checked);
});

또는

$checkBoxes = $(".checkBoxes");
$("#checkAll").change(function (e) {
    $checkBoxes.prop("checked", this.checked);
});   

또는

<input onchange="toggleAll(this)">
function toggleAll(sender) {
    $(".checkBoxes").prop("checked", sender.checked);
}

8

jQuery 1.6부터는 .prop(function)발견 된 각 요소의 확인 된 상태를 토글하는 데 사용할 수 있습니다.

$("input[name=recipients\\[\\]]").prop('checked', function(_, checked) {
    return !checked;
});

훌륭한 답변입니다. 밑줄을 첫 번째 매개 변수로 전달하는 것에 대해 더 많이 알고 있습니까? 그것에 대해 더 배울 수있는 곳은 어디입니까?
— user1477388

1
편집 : 분명히, 그것은 본질적으로 null stackoverflow.com/questions/11406823/…
— user1477388

8

이 플러그인을 사용하십시오 :

$.fn.toggleCheck  =function() {
       if(this.tagName === 'INPUT') {
           $(this).prop('checked', !($(this).is(':checked')));
       }

   }

그때

$('#myCheckBox').toggleCheck();

2

확인란을 토글 해야하는 이미지라고 가정하면, 이것은 나를 위해 작동합니다

<img src="something.gif" onclick="$('#checkboxid').prop('checked', !($('#checkboxid').is(':checked')));">
<input type="checkbox" id="checkboxid">

4
이것이 첫 번째 대답이므로 jQuery 코드를 문서 준비 핸들러에 배치하고 마크 업이 아닌 jQuery 코드를 배치하는 것과 같이 질문에 포스터가 사용한 패턴을 따르는 것이 가장 좋습니다. 그렇게하지 말아야 할 이유가 있다면 그 이유에 대한 설명을 추가하십시오.
— Mark Schultheiss

2

특정 조건에서 Check-all 확인란이 자체적 으로 업데이트되어야합니다 . 클릭하려고 '# 선택 - 모든 teammembers' 다음을 선택 취소 몇 가지 항목을 선택 모두 다시 클릭합니다. 불일치를 볼 수 있습니다. 이를 방지하려면 다음 트릭을 사용하십시오.

  var checkBoxes = $('input[name=recipients\\[\\]]');
  $('#select-all-teammembers').click(function() {
    checkBoxes.prop("checked", !checkBoxes.prop("checked"));
    $(this).prop("checked", checkBoxes.is(':checked'));
  }); 

BTW 모든 확인란 DOM 개체는 위에서 설명한대로 캐시되어야합니다.


2

다음은 html5 및 레이블이있는 확인란을 선택하지 않고 확인란을 전환하는 jQuery 방법입니다.

 <div class="checkbox-list margin-auto">
    <label class="">Compare to Last Year</label><br>
    <label class="normal" for="01">
       <input id="01" type="checkbox" name="VIEW" value="01"> Retail units
    </label>
    <label class="normal" for="02">
          <input id="02" type="checkbox" name="VIEW" value="02">  Retail Dollars
    </label>
    <label class="normal" for="03">
          <input id="03" type="checkbox" name="VIEW" value="03">  GP Dollars
    </label>
    <label class="normal" for="04">
          <input id="04" type="checkbox" name="VIEW" value="04">  GP Percent
    </label>
</div>

  $("input[name='VIEW']:checkbox").change(function() {
    if($(this).is(':checked')) {  
         $("input[name='VIEW']:checkbox").prop("checked", false);
     $("input[name='VIEW']:checkbox").parent('.normal').removeClass("checked");
         $(this).prop("checked", true);
         $(this).parent('.normal').addClass('checked');
    }
    else{
         $("input[name='VIEW']").prop("checked", false);
         $("input[name='VIEW']").parent('.normal').removeClass('checked');
    }    
});

http://www.bootply.com/A4h6kAPshx


1

각 상자를 개별적으로 토글하려면 (또는 하나의 상자 만 작동) :

.each ()를 사용하는 것이 좋습니다. 다른 일이 일어나기를 원하면 수정하기 쉽고 여전히 비교적 짧고 읽기 쉽습니다.

예 :

// toggle all checkboxes, not all at once but toggle each one for its own checked state:
$('input[type="checkbox"]').each(function(){ this.checked = ! this.checked });

// check al even boxes, uncheck all odd boxes:
$('input[type="checkbox"]').each(function(i,cb){ cb.checked = (i%2 == 0); });

// set all to checked = x and only trigger change if it actually changed:
x = true;
$('input[type="checkbox"]').each(function(){
    if(this.checked != x){ this.checked = x; $(this).change();}  
});

참고로 ... 모든 사람들이 왜 .attr () 또는 .prop ()을 사용하여 물건을 검사하지 않는지 확실하지 않습니다.

내가 아는 한 element.checked는 모든 브라우저에서 항상 동일하게 작동합니까?


1
jQuery("#checker").click(function(){
    jQuery("#mydiv :checkbox").each(function(){
        this.checked = true;
    });
});
jQuery("#dechecker").click(function(){
    jQuery("#mydiv :checkbox").each(function(){
        this.checked = false;
    });
});
jQuery("#checktoggler").click(function(){
    jQuery("#mydiv :checkbox").each(function(){
        this.checked = !this.checked;
    });
});

;)


1

이렇게 쓸 수도 있습니다

$(function() {
    $("#checkbox-toggle").click(function() {
        $('input[type=checkbox][name=checkbox_id\\[\\]]').click();
    });
});

사용자가 ID가 '# checkbox-toggle'인 버튼을 클릭하면 확인란의 클릭 이벤트를 호출하면됩니다.


1

더 나은 접근 방식과 UX

$('.checkall').on('click', function() {
   var $checks  = $('checks');
   var $ckall = $(this);

    $.each($checks, function(){
        $(this).prop("checked", $ckall.prop('checked'));
    });
});

$('checks').on('click', function(e){
   $('.checkall').prop('checked', false);
});

1
<table class="table table-datatable table-bordered table-condensed table-striped table-hover table-responsive">
<thead>
    <tr>
        <th class="col-xs-1"><a class="select_all btn btn-xs btn-info"> Select All </a></th>
        <th class="col-xs-2">#ID</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td><input type="checkbox" name="order333"/></td>
        <td>{{ order.id }}</td>
    </tr>
    <tr>
        <td><input type="checkbox" name="order334"/></td>
        <td>{{ order.id }}</td>
    </tr>
</tbody>                  
</table>

시험:

$(".table-datatable .select_all").on('click', function () {
    $("input[name^='order']").prop('checked', function (i, val) {
        return !val;
    });
});

1

이것은 나를 위해 아주 잘 작동합니다.

   $("#checkall").click(function() {
       var fruits = $("input[name=fruits\\[\\]]");
        fruits.prop("checked", $(this).prop("checked"));
    });

1
"checked"속성에 이미 가지고있는 것과 동일한 값을 제공한다는 것을 알고 있습니까? 조금 창피하지 않습니까? 당신은 분명히 !앞에 서명을하려고했다 ..
— vsync

1

가장 기본적인 예는 다음과 같습니다.

// get DOM elements
var checkbox = document.querySelector('input'),
    button = document.querySelector('button');

// bind "cilck" event on the button
button.addEventListener('click', toggleCheckbox);

// when clicking the button, toggle the checkbox
function toggleCheckbox(){
  checkbox.checked = !checkbox.checked;
};
<input type="checkbox">
<button>Toggle checkbox</button>


1

간단히 이것을 사용할 수 있습니다

$("#chkAll").on("click",function(){
    $("input[name=checkBoxName]").prop("checked",$(this).prop("checked"));
});

0

내 생각에, 정상적인 변종을 제안한 가장 오른쪽 사람은 GigolNet Gigolashvili이지만 더 아름다운 변종을 제안하고 싶습니다. 확인해 봐

$(document).on('click', '.fieldWrapper > label', function(event) {
    event.preventDefault()
    var n = $( event.target ).parent().find('input:checked').length
    var m = $( event.target ).parent().find('input').length
    x = n==m? false:true
    $( event.target ).parent().find('input').each(function (ind, el) {
        // $(el).attr('checked', 'checked');
        this.checked = x
    })
})

0

각각 true 또는 false 대신 'checked'또는 null을 설정하면 작업이 수행됩니다.

// checkbox selection
var $chk=$(':checkbox');
$chk.prop('checked',$chk.is(':checked') ? null:'checked');

0

이 코드는 웹 템플릿에 사용 된 토글 스위치 애니메이터를 클릭하면 확인란을 토글합니다. 코드에서 사용 가능한 ".onoffswitch-label"을 바꾸십시오. "checkboxID"는 여기서 토글 된 확인란입니다.

$('.onoffswitch-label').click(function () {
if ($('#checkboxID').prop('checked')) 
 {
   $('#checkboxID').prop('checked', false);
 }
else 
 {
   $('#checkboxID').prop('checked', true);
 }
});

-3

더 쉬운 방법이 있습니다

먼저 확인란에 클래스 예 'id_chk'를 지정하십시오.

그런 다음 확인란 내부에서 'id_chk'체크 상자 상태를 제어합니다.

<input type='checkbox' onchange='js:jQuery(".id_chk").prop("checked", jQuery(this).prop("checked"))' />

그게 다야, 이것이 도움이되기를 바랍니다.

당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.