확인란 켜기 / 끄기
나는 다음을 가지고있다 :
$(document).ready(function()
{
$("#select-all-teammembers").click(function() {
$("input[name=recipients\\[\\]]").attr('checked', true);
});
});
id="select-all-teammembers"
클릭하면 체크 표시와 체크 해제 사이를 전환 하고 싶습니다 . 아이디어? 수십 줄의 코드가 아닙니까?
당신은 쓸 수 있습니다:
$(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()
다 의미가 우수 하므로 일반적으로이 상황에서 선호됩니다.
//this toggles the checkbox, and fires its event if it has
$('input[type=checkbox]').trigger('click');
//or
$('input[type=checkbox]').click();
나는 이것이 오래되었다는 것을 알고 있지만 그 토글 에서 약간 모호한 질문은 각 확인란이 상태를 토글해야한다는 것을 의미 할 수 있습니다. 3을 체크하고 2를 체크하지 않으면, 토글하면 처음 3을 체크하지 않고 마지막 2를 체크합니다.
이를 위해 각 확인란의 상태를 전환하지 않고 모든 확인란을 동일한 상태로 만드는 솔루션은 작동하지 않습니다. $(':checkbox').prop('checked')
많은 확인란을 선택 하면 모든 .checked
이진 속성 사이의 논리 AND가 반환됩니다 false
.
.each()
각 확인란 상태를 모두 동일하게 만드는 것이 아니라 실제로 각 상태를 토글하려는 경우 사용해야 합니다. 예 :
$(':checkbox').each(function () { this.checked = !this.checked; });
속성이 모든 브라우저에 존재 $(this)
하므로 핸들러 내부에 필요하지 않습니다 .checked
.
여기 또 다른 방법이 있습니다.
$(document).ready(function(){
$('#checkp').toggle(
function () {
$('.check').attr('Checked','Checked');
},
function () {
$('.check').removeAttr('Checked');
}
);
});
클릭을 발생시키는 것이 더 간단하다고 생각합니다.
$("#select-all-teammembers").click(function() {
$("input[name=recipients\\[\\]]").trigger('click');
});
jQuery 1.6부터는 .prop(function)
발견 된 각 요소의 확인 된 상태를 토글하는 데 사용할 수 있습니다.
$("input[name=recipients\\[\\]]").prop('checked', function(_, checked) {
return !checked;
});
이 플러그인을 사용하십시오 :
$.fn.toggleCheck =function() {
if(this.tagName === 'INPUT') {
$(this).prop('checked', !($(this).is(':checked')));
}
}
그때
$('#myCheckBox').toggleCheck();
내가 생각할 수있는 가장 좋은 방법.
$('#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);
}
확인란을 토글 해야하는 이미지라고 가정하면, 이것은 나를 위해 작동합니다
<img src="something.gif" onclick="$('#checkboxid').prop('checked', !($('#checkboxid').is(':checked')));">
<input type="checkbox" id="checkboxid">
특정 조건에서 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 개체는 위에서 설명한대로 캐시되어야합니다.
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
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;
});
});
;)
이렇게 쓸 수도 있습니다
$(function() {
$("#checkbox-toggle").click(function() {
$('input[type=checkbox][name=checkbox_id\\[\\]]').click();
});
});
사용자가 ID가 '# checkbox-toggle'인 버튼을 클릭하면 확인란의 클릭 이벤트를 호출하면됩니다.
더 나은 접근 방식과 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);
});
<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;
});
});
가장 기본적인 예는 다음과 같습니다.
// 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>
간단히 이것을 사용할 수 있습니다
$("#chkAll").on("click",function(){
$("input[name=checkBoxName]").prop("checked",$(this).prop("checked"));
});
각 상자를 개별적으로 토글하려면 (또는 하나의 상자 만 작동) :
.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는 모든 브라우저에서 항상 동일하게 작동합니까?
내 생각에, 정상적인 변종을 제안한 가장 오른쪽 사람은 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
})
})
각각 true 또는 false 대신 'checked'또는 null을 설정하면 작업이 수행됩니다.
// checkbox selection
var $chk=$(':checkbox');
$chk.prop('checked',$chk.is(':checked') ? null:'checked');
이것은 나를 위해 아주 잘 작동합니다.
$("#checkall").click(function() {
var fruits = $("input[name=fruits\\[\\]]");
fruits.prop("checked", $(this).prop("checked"));
});
이 코드는 웹 템플릿에 사용 된 토글 스위치 애니메이터를 클릭하면 확인란을 토글합니다. 코드에서 사용 가능한 ".onoffswitch-label"을 바꾸십시오. "checkboxID"는 여기서 토글 된 확인란입니다.
$('.onoffswitch-label').click(function () {
if ($('#checkboxID').prop('checked'))
{
$('#checkboxID').prop('checked', false);
}
else
{
$('#checkboxID').prop('checked', true);
}
});
더 쉬운 방법이 있습니다
먼저 확인란에 클래스 예 'id_chk'를 지정하십시오.
그런 다음 확인란 내부에서 'id_chk'체크 상자 상태를 제어합니다.
<input type='checkbox' onchange='js:jQuery(".id_chk").prop("checked", jQuery(this).prop("checked"))' />
그게 다야, 이것이 도움이되기를 바랍니다.
참고 URL : https://stackoverflow.com/questions/4177159/toggle-checkboxes-on-off
'Programing' 카테고리의 다른 글
WordPress에 대한 올바른 파일 권한 (0) | 2020.02.26 |
---|---|
소수점 이하 두 자리로 반올림되는 자바 스크립트 수학 (0) | 2020.02.25 |
HTTPS를 통한 HttpClient를 사용하여 모든 인증서 신뢰 (0) | 2020.02.25 |
Android에서 ListViews 사이의 줄을 어떻게 제거합니까? (0) | 2020.02.25 |
확인란이 선택된 경우 jQuery (0) | 2020.02.25 |