HTML DOM의 defaultChecked 속성은 HTML 체크박스 요소에 설정된 checked 속성의 기본값을 반환합니다. 이 속성을 활용하면 페이지가 로드될 때 체크박스가 기본적으로 선택되어 있었는지 여부를 JavaScript로 확인할 수 있습니다.
문법(Syntax)
defaultChecked 속성의 기본 문법은 다음과 같습니다.
object.defaultChecked
예제(Example)
아래 예제를 통해 defaultChecked 속성이 실제로 어떻게 동작하는지 살펴보겠습니다.
<!DOCTYPE html>
<html>
<head>
<title>HTML DOM checked property</title>
<style>
body{
text-align:center;
}
p{
font-size:1.5rem;
color:#ff8741;
}
input{
width:30px;
height:30px;
}
button{
background-color:#db133a;
color:#fff;
padding:8px;
border:none;
width:180px;
margin:0.5rem;
border-radius:50px;
outline:none;
font-weight:bold;
}
.show-msg{
color:#db133a;
font-size:1.5rem;
font-weight:bold;
}
</style>
</head>
<body>
<h1>checked Property Example</h1>
<p>Are you smart?</p>
<input type="checkbox" checked>
<br>
<button onclick="check()">Lets Check? Click me</button>
<div class="show-msg"></div>
<script>
function check() {
var input = document.querySelector("input");
var showMsg = document.querySelector(".show-msg");
if(input.defaultChecked === true){
showMsg.innerHTML="You are right!You are smart by default";
} else {
showMsg.innerHTML="Hmmmmm!You are not smart by default";
}
}
</script>
</body>
</html>실행 결과(Output)
위 코드를 실행하면 다음과 같은 화면이 출력됩니다.

화면에 표시된 "Lets Check? Click me" 버튼을 클릭하면, 해당 체크박스가 기본적으로 선택(checked) 상태였는지 여부가 확인됩니다.

defaultChecked와 checked의 차이점
defaultChecked 속성과 checked 속성은 혼동하기 쉽지만 그 역할이 다릅니다.
- checked: 사용자가 체크박스를 조작하면 실시간으로 값이 변경되는 현재 상태(current state)를 나타냅니다.
- defaultChecked: HTML 마크업에서 처음 지정한
checked속성의 초기값을 그대로 유지하며, 사용자 조작과 무관하게 변하지 않습니다.
따라서 폼을 리셋(reset)할 때 원래 상태로 되돌리거나, 초기 렌더링 시의 체크 여부를 판별해야 하는 경우에는 defaultChecked 속성을 사용하는 것이 적합합니다.