[jQuery] prop() 함수

형이·2023년 8월 21일

jQuery

목록 보기
14/14
post-thumbnail

📝 jQuery

🖥️ 1. 프로퍼티를 제어하는 prop() 함수

  • src, width, .. -> 값을 갖는 속성 : attr(key, value)
  • 값을 갖지 않는 속성 -> prop
  • 별도의 값 없이 이름만 명시하는 속성

    	$("셀렉터").prop("disabled", true);
    	-> HTML 태그에서 disabled 속성을 부여하면
    	   해당 요소가 비활성화 처리가 된다.
    
    	$("셀렉터").prop("checked", true);
    	-> input 태그에서 checked 속성이 부여되면 선택상태가 되므로
    	   jQuery에서는 true값을 부여해야 체크가 된다.

📝 예제

EX1) disabled

	<head>
    ...
    <script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
    <style>
        input[disabled]{ background-color: grey; }
    </style>
</head>
<body>
    <label>
        입력하기 
        <input type="checkbox" id="input_enable"/>                
    </label>
    <input type="text" name="input" id="input" disabled/>
    <script>
        $("#input_enable").change(function(){
            let now = $("#input").prop('disabled'); // true/false
            $("#input").prop('disabled', !now);
            // 입력 가능한 상태라면
            if( $("#input").prop('disabled') == false){ 
                $("#input").focus();
            }
        });
    </script>
    
</body>

EX) checkall

	<head>
    ...
    <script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>
    <label>전체선택
        <input type="checkbox" id="all_check"/>                
    </label>
    <hr/>
    <label>
        <input type="checkbox" class="hobby" value="soccor"/>축구
    </label>
    <label>
        <input type="checkbox" class="hobby" value="basketball"/>농구
    </label>
    <label>
        <input type="checkbox" class="hobby" value="baseball"/>야구
    </label>
    <script>
        $("#all_check").change(function(){
            $(".hobby").prop('checked', $(this).prop('checked'));
        });
    </script>
</body>

0개의 댓글