Development/JSP, JS, JQUERY
checkbox 관련
루루지
2021. 10. 4. 12:05
반응형
[jQuery]html 체크박스 체크시 이벤트 동작 발생
예전에도 input type="checkbox" 의 이벤트 실행해 대해서 포스팅 한 적 있습니다. 개인적으로 체크박스로 만들어 진 것은 제어하기가 편해서 많이 사용 하는 것 같네요. 오늘은 간단하게 체크박스 클
cocosoft.kr
https://openlife.tistory.com/381
갯수 구하기
checkbox 갯수 구하기
$("input[type='checkbox']").length
checkbox 체크 갯수 구하기
$("input[type='checkbox']:checked").length
checkbox에 이미지 입히기
// jsp
// input태그의 id와 label의 for을 매핑시킨다.
<input id="check" name="checkList" type="checkbox" />
<label for="check">체크테스트</label>
// css
// 아래와 같이 기본 input박스는 없애고, input다음에 바로 label이 올경우 체크 활성화, 비활성화 이미지를 넣어준다.
input[type=checkbox] {
display: none;
}
input[type=checkbox]+label {
background: url(/images/icons/upcycle/check_dim.png) no-repeat 0 0px / contain;
}
input[type=checkbox]:checked+label {
background: url(/images/icons/upcycle/check.png) no-repeat 0 0px / contain;
}
checkbox 상위 태그 영역 클릭시 이벤트
체크박스 영역만이 아니라 위의 이미지 박스 영역 전체를 선택할 수 있게 하기 위해 추가.
<article name="ch-click">
<input id="check" name="checkList" type="checkbox" />
<label for="check"></label>
</article>
....여러개의 name="ch-click" article태그가 있다고 가정...
$("article[name='ch-click']").on('click', function(){
// 클릭한 article의 하위 체크박스 상태 변경
if ($(this).children('input').prop('checked')) {
$(this).removeClass("check-ok");
$(this).children('input').prop('checked',false);
} else {
$(this).addClass("check-ok");
$(this).children('input').prop('checked',true);
}
}
// css
.check-ok {
border: 1px solid #FF5C35 !important;
color: #FF5C35;
}
전체 체크 선택, 해지
//html
<input type="checkbox" id="ratingAll" value="" >전체</input>
<input type="checkbox" name="rating" value="5" >★★★★★</input>
<input type="checkbox" name="rating" value="4" >★★★★</input>
<input type="checkbox" name="rating" value="3" >★★★</input>
<input type="checkbox" name="rating" value="2" >★★</input>
<input type="checkbox" name="rating" value="1" >★</input>
// script
$("#ratingAll").click(function() {
if ($(this).is(":checked")) {
$('input[name="rating"]').prop("checked", true);
} else {
$('input[name="rating"]').prop("checked", false);
}
});
prop대신 attr을 사용했을 때의 문제점.
=> 전체만 클릭하면 문제없어 보이지만, 다른 것들의 체크해제 or 체크하면 그 후부턴 전체를 눌러도 정상적으로 작동x