본문 바로가기

일경험

[국민취업지원제도 일경험프로그램 5일차] 스크립트 체크박스

반응형

5 일차 특이사항 

1. SQLD 접수 완료

신청완료


2. 새로운 과제 시작. 스크립트로 체크박스 기능을 구현한다. 

 

새로운 과제 (스크립트 체크박스 만들기) 

1. 스크립트 체크박스  만들기 

자바스크립트 체크박스
조건에 맞게 설계하기

2. 조건 

스크립트 체크박스
체크박스

전체 버튼 누르면 전체 체크박스가 체크된다. 

전체 버튼 누르고 나머지 버튼 중 하나가 체크 해제되면 전체버튼이 해제된다. 반대로 체크박스가 전부 체크되면 전체 체크된다.  

글자를 눌러도 체크박스에 체크가 된다. 

[버튼]을 눌렀을 때, 체크박스 갯수가 3개 이상인 경우만 통과, 아니면 실패. 체크를 하나도 하지 않았을 경우도 체크 

⑤ 체크박스 클릭시 해당하는 text가 출력된다. 클릭 해제시 text가 사라진다. 

 

3. 내가 만든 소스코드 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.net.URLDecoder" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>SingUP</title>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
</head>
<body>
<input type="checkbox" id="chk1" name="box" value="1"><label for="chk1">전체</label><button id="Button1">버튼</button><br> 
<input type="checkbox" id="chk2" class="textprint" name="box" value="2"><label for="chk2">서울</label>	
<input type="checkbox" id="chk3" class="textprint" name="box" value="3"><label for="chk3">인천</label>
<input type="checkbox" id="chk4" class="textprint" name="box" value="4"><label for="chk4">경기</label>
<input type="checkbox" id="chk5" class="textprint" name="box" value="5"><label for="chk5">강원</label>
<input type="checkbox" id="chk6" class="textprint" name="box" value="6"><label for="chk6">부산</label>
<input type="checkbox" id="chk7" class="textprint" name="box" value="7"><label for="chk7">대전</label>
<input type="checkbox" id="chk8" class="textprint" name="box" value="8"><label for="chk8">전남</label>
<input type="checkbox" id="chk9" class="textprint" name="box" value="9"><label for="chk9">제주</label>
<input type="checkbox" id="chk10" class="textprint" name="box" value="10"><label for="chk10">평양</label><br>
<div id="textprint"></div>
<script>
    $(document).ready(function() {
        
        var textarr = [];	//저장공간
        
        // 체크박스를 클릭할 때 해당 label 텍스트 저장
        $(document).on("click", ".textprint", function() {
            var label = $(this).next("label").text();
            
            if ($(this).is(":checked")) {
                textarr.push(label);
            } else {
                var index = textarr.indexOf(label);
                if (index !== -1) {
                    textarr.splice(index, 1);
                }
            }
            
            $("#textprint").text(textarr.join(" "));
        });
        
        //전체 체크시 모든 체크박스 체크됨 
        var chkList = $("input[name=box]");    //같은 name은 배열로 인식한다. 한번에 통제할 수 있음. 
        
        $("#chk1").click(function(){ 
            if($(this).is(":checked")){
                chkList.prop("checked", true);    //prop을 사용하면 속성값을 가져오고 직접 설정할 수 있다. true로 설정하면 체크됨. 
            } else {
                chkList.prop("checked", false);
            }
        });
        
        //나머지 버튼 중 하나가 체크해제되면 전체 체크 해제됨. 
        chkList.not("#chk1").click(function(){ 
            if(!$(this).is(":checked")){
                $("#chk1").prop("checked", false); 
            }
        });
        
        //체크박스가 모두 클릭되면 전체 체크됨 
        $("input[name=box]").not("#chk1").click(function() {
            var allChecked = true;
            
            $("input[name=box]").not("#chk1").each(function() {    // chk1을 제외한 나머지 배열들을 각각 확인한다.
                if (!$(this).is(":checked")) {                    // 하나라도 체크가 되어 있지 않다면 false를 반환한다. 
                    allChecked = false;
                }
            });
            
            $("#chk1").prop("checked", allChecked);                // false를 받으면 전체 체크x, true를 받으면 전체 체크됨 
        });
        
        //버튼을 누르면 유효성 검사 실시. 체크박스가 3개 이상이어야 통과 아니면 실패. 
        $("#Button1").click(function(){
            var checkedCount = $("input[name=box]:checked").length;
            if(checkedCount == 0){
                alert("체크해주세요.");
            } else if(checkedCount >= 3){
                alert("성공");
            } else {
            	alert("실패");
            }
        });
    });
</script>
</body>
</html>

 

4. 팀장님 코드 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
<script>
	$(function(){
		// 전체 체크시 다른 항목 모두 체크
		$("#all").click(function(){
			
			if($("#all").is(":checked")){
				$("[name=chk]").prop("checked",true);
			}else{
				$("[name=chk]").prop("checked",false);
			}
		})
		// 체크 박스 개수 = 체크박수 전체 개수(length)와 같다면 전체 체크 
		$("[name=chk]").click(function(){
			var checkbox = $("[name=chk]").length;
			var checked = $("[name=chk]:checked").length;
			
			if(checkbox == checked){
				$("#all").prop("checked",true);
			}else{
				$("#all").prop("checked",false);
			}
			//체크된 박스가 있다면 div태그에 체크된 박스의 value값을 추가합니다. 
			if($(this).is(":checked")){
				$("#dvTxt").append($(this).val());
			}else{
				$("#dvTxt").text( $("#dvTxt").text().replace($(this).val(), "") );
			}
		})
		//name이 chk인 input태그의 체크된 개수를 변수에 저장합니다.
		$("#btn").click(function(){
			var checked = $("[name=chk]:checked").length;
			
			// 0개인 경우, 3개 미만인 경우, 전체 체크된 경우 alert 
			if(checked == 0){
				alert("항목 체크");
			}else if(checked < 3 || $("#all").is(":checked") ){
				alert("성공");
			}else{
				alert("실패");
			}
			
		})
	})
</script>
</head>
<body>
<div>
	<input type = "checkbox" name = "all" id = "all"><label for = "all">전체</label>
	<input type = "button" name = "btn" id = "btn" value = "버튼">
</div>
<div>
	<input type = "checkbox" name = "chk" id = "chk1" value= "체크1"><label for = "chk1">서울</label>
	<input type = "checkbox" name = "chk" id = "chk2" value= "체크2"><label for = "chk2">인천</label>
	<input type = "checkbox" name = "chk" id = "chk3" value= "체크3"><label for = "chk3">경기</label>
	<input type = "checkbox" name = "chk" id = "chk4" value= "체크4"><label for = "chk4">강원</label>
	<input type = "checkbox" name = "chk" id = "chk5" value= "체크5"><label for = "chk5">부산</label>
	<input type = "checkbox" name = "chk" id = "chk6" value= "체크6"><label for = "chk6">광주</label>
	<input type = "checkbox" name = "chk" id = "chk7" value= "체크7"><label for = "chk7">대구</label>
	<input type = "checkbox" name = "chk" id = "chk8" value= "체크8"><label for = "chk8">제주도</label>
	<input type = "checkbox" name = "chk" id = "chk9" value= "체크9"><label for = "chk9">미국</label>
</div>
<div id = "dvTxt"></div>
</body>
</html>

5. attr() vs prop() 메서드의 차이점 

attr은 속성이 직접적으로 조작한다. attr은 속성을 추가하거나 변경 가능하다. prop는 속성값의 직접적인 변화 없이 액션만 취한다. 

 

.attr 예시 코드 : 버튼을 클릭하면 버튼type이 text로 바뀐다. 

<input type = "button" name = "test" id = "test" value = "test">


$("#test").click(function(){$("#test").attr("type","text");})

 

6. .prop("checked")   VS   .is(":checked")

 

부족했던 것, 느낀 점

1. 체크박스 클릭한 순서대로 text가 출력되어야 하는데 안 된다. 해결 못하고 있음.... 답답. 

 

2. 내가 짠 코드와 팀장님이 짠 코드가 많이 다르다. 팀장님 코드가 훨씬 이해하기 쉽다. 내 것은 조잡하다. 

 

3. 팀장님의 조언 

 

<label></label>을 붙여주고 for 속성을 주면 text와 체크박스가 묶인다. 보통 이렇게 사용함. 

 

readonly, disabled도 액션은 있지만 prop를 쓰면 true or false. 

attribute는 직접적으로 속성을 추가해준다. 

 

this를 지정해주면 focus된다. 

스크립트가 반응이 없다? 콘솔창을 봐라. 오타 가능성 많음. 

 

text 추가할 때,  append를 쓸 수 있다. 

 

 

 

 

반응형