[javascript] jQuery 체크박스 체크/해제

skoh·2022년 12월 21일
0

■ 체크박스 여러개를 일괄적으로 체크하고 체크해제하고 싶을 때


<예시>

<input type="checkbox" id="agree0" name="agree0">전체체크 <br>
<input type="checkbox" id="agree1" name="agree1">체크1
<input type="checkbox" id="agree2" name="agree2">체크2

■ 코드

  1. 전체체크 클릭 시 체크1, 체크2 모두 체크/체크해제
  • input name을 사용할 때
$("input[name=agree0]").click(function(){
	if($("input[name=agree0]").is(":checked")){
		$("input[name=agree1]").prop("checked",true);
		$("input[name=agree2]").prop("checked",true);
	}
	else{
		$("input[name=agree1]").prop("checked",false);
		$("input[name=agree2]").prop("checked",false);
	}
});
  • id 사용할 때
$("#agree0").click(function(){
	if($("#agree0").is(":checked")){
		$("#agree1").prop("checked",true);
		$("#agree2").prop("checked",true);
	}
	else{
		$("#agree1").prop("checked",false);
		$("#agree2").prop("checked",false);
	}
});


  1. 체크1, 체크2 모두 체크하면 전체체크 체크/ 체크1, 체크2 둘 중 하나라도 체크해제되면 전체체크도 체크해제
  • input name을 사용할 때
$("input[name=agree1]").click(function(){
	if($("input[name=agree1]").is(":checked") && $("input[name=agree2]").is(":checked")){
		$("input[name=agree0]").prop("checked",true);
	} else {
		$("input[name=agree0]").prop("checked",false);
	}
});

$("input[name=agree2]").click(function(){
	if($("input[name=agree1]").is(":checked") && $("input[name=agree2]").is(":checked")){
		$("input[name=agree0]").prop("checked",true);
	} else {
		$("input[name=agree0]").prop("checked",false);
	}
});
  • id 사용할 때
$("#agree1").click(function(){
	if($("#agree1").is(":checked") && $("#agree2").is(":checked")){
		$("#agree0").prop("checked",true);
	} else {
		$("#agree0").prop("checked",false);
	}
});

$("#agree2").click(function(){
	if($("#agree1").is(":checked") && $("#agree2").is(":checked")){
		$("#agree0").prop("checked",true);
	} else {
		$("#agree0").prop("checked",false);
	}
});

0개의 댓글