본문 바로가기

[jQuery] checkbox 제어하기

안자매 2022. 6. 27.
반응형

 

개인적으로 공부하면서 기록하는 공간으로
잘못된 정보는 댓글을 통해 알려주시면 감사하겠습니다 :-)

▪ ▪ ▪ ▪ ▪

 

 

Checkbox

1. checked 여부 확인

$('input[id=checkId01]').is(':checked');

checkbox에 check가 되어있다면 true, 아니면 false로 리턴 된다.

 

2. checked 개수

$('input[name=checkName]:checked').length;

check된  checkbox의 개수를 리턴한다.

 

3. checkbox 변경 감지

$('input[name=checkName]').on('change', function() {
  /* 실행문 */
});

$('input[name=checkName]').on('click', function () {
  /* 실행문 */
});

 

4. checked 추가 및 checked 해제

// checked 추가
$('input[id=checkId01]').prop('checked', true);

// checked 해제
$('input[id=checkId01]').prop('checked', false);
// 또는
$('input[id=checkId01]').removeAttr('checked');

 

5. disabled option 추가

$('input[id=checkId02]').prop('disabled', true);

 

6. checkbox value 값 

$('input[id=checkId01]').val();

// 전체 checkbox
let values = '';
$('input[name=checkName]:checked').each(function() {
    values += $(this).val() + ", ";
});

value 값을 알아내고 싶은 경우 val()을 사용한다.

 

 

7. 전체 선택 및 전체선택 해제

$('#checkAll').on('click', function() {
  if ($('#checkAll').is(':checked')){
    $('input[name=checkName]').prop('checked', true);
  } else {
    $('input[name=checkName]').prop('checked', false);
  }
});

 

 

구현하기



check를 한 후, 아래의 버튼을 클릭해주세요 !

checked 여부 checked 개수 checked 추가 checked 해제 disabled 추가&해제 checked value

 

 

 

Checkbox에 style 추가하기

위에 제가 구현해놓은 코드와 같이 checkbox에 style을 입히시고 싶은 분은 아래의 코드를 참고해주세요 !

.checkwrap label { position:relative; margin-left:15px; margin-bottom:0px; color:#b0b1b0; font-weight: normal }
.checkwrap input[type="checkbox"] { display:none; }
.checkwrap input[type="checkbox"] + label:before {
	content:"\f058";
	font-family:"Font Awesome 5 free"; 
	position:relative; top:0px; left:0px;
	display:inline-block;
	margin-right:5px;
}
.checkwrap input[type="checkbox"]:checked + label { color:#5B92E4; font-weight:bold; }
.checkwrap input[type="checkbox"]:checked + label:before {
	content:"\f058";
	font-family:"Font Awesome 5 free"; 
	position:relative; top:0px; left:0px;
	display:inline-block;
	margin-right:5px;
	color:#5B92E4;
}

 

 

 

댓글