Developer's Development

[HTML] checkbox control (jQuery/search area) 본문

개발/HTML

[HTML] checkbox control (jQuery/search area)

mylee99 2023. 5. 2. 20:51
input type > radio와 checkbox의 차이

- radio : 단일 선택만 가능

- checkbox : 중복 선택도 가능

 

HTML
  • <label></label>로 <input type="checkbox"/>를 감싸면 체크박스가 아닌 텍스트를 클릭해도 선택이 가능하다.
<label><input type="checkbox" name="status" value=""><i class="check-icon"></i>전체</label>
<label><input type="checkbox" name="status" value="IF"><i class="check-icon"></i>발급완료</label>
<label><input type="checkbox" name="status" value="IC"><i class="check-icon"></i>발급취소</label>
<label><input type="checkbox" name="status" value="RF"><i class="check-icon"></i>환불</label>

 

jQuery
  • '전체'를 선택하면 체크되어 있던 다른 값들을 해제하고, 다른 값들을 선택하면 '전체'를 해제
$("[name=status]").change(function() {
	if($("input[name=status]:checked").length > 1) {
    	if($(this).val() == "") {
        	$("input[name=status]:gt(0)").prop("checked",false);
        } else {
        	$("input[name=status]:eq(0)").prop("checked",false);
        }
    }
});
  • 체크박스 선택 후 검색 시 단일 선택, 복수 선택 값 처리
search = function() {
	/*if($("input[name=status]:checked").length > 1) {
    	var stat = "";
        $("input[name=status]:checked").each(function(e) {
        	if(this.value == null || this.value == "") {
            	return false;
            } else {
            	if(e == 0) stat = this.value;
                else {
                	stat += "," + this.value;
                }
            }
        });
    } else {
    	stat = $("input[name=status]:checked").val();
    }*/
    
    //2023-06-12 추가(코드 단축)
    let stat = new Array();
    $("input:checkbox[name=status]").each(function() {
    	if(this.checked) {
        	stat.push($(this).val());
        }
    });
}
  • 문서 로드 시 저장되어 있는 체크박스 값이 있으면 체크상태 유지, 없으면 '전체' 체크
$(document).ready(function() {
	var searchState = $("#form").find("input[name='searchState']").val();
    if(searchState != "") {
    	const state = searchState.split(",");
        for(let i=0; i<state.length; i++) {
        	$("input[name=status][value="+state[i]+"]").prop('checked',true);
        }
    } else {
    	$("input[name=status]:eq(0)").prop("checked",true);
    }
});

 

See the Pen checkbox by LEE MIN YOUNG (@mylee99125) on CodePen.

Comments