HTML DOM의 readOnly 속성은 HTML 문서에서 숫자 입력(type="number") 필드가 읽기 전용 상태인지 여부를 확인하고, 필요에 따라 이를 변경할 수 있게 해주는 기능입니다.
readOnly 속성이란?
readOnly 속성은 불리언(Boolean) 값을 다룹니다. 값이 true이면 사용자가 해당 입력 필드의 내용을 수정할 수 없으며, false이면 자유롭게 편집할 수 있습니다. 읽기 전용 필드는 포커스를 받을 수 있고 폼 제출 시 값이 함께 전송된다는 점에서 disabled 속성과 차이가 있습니다.
문법
다음은 readOnly 속성의 기본 문법입니다 −
readOnly 값 가져오기
object.readOnly
readOnly 값 설정하기
object.readOnly = true | false
예제
다음은 input number 요소의 readOnly 속성을 활용한 실전 예제입니다 −
<!DOCTYPE html>
<html>
<head>
<style>
html{
height:100%;
}
body{
text-align:center;
color:#fff;
background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) center/cover no-repeat;
height:100%;
}
p{
font-weight:700;
font-size:1.1rem;
}
input{
display:block;
width:35%;
border:2px solid #fff;
background-color:transparent;
color:#fff;
font-weight:bold;
padding:8px;
margin:1rem auto;
outline:none;
}
.btn{
background:#0197F6;
border:none;
height:2rem;
border-radius:2px;
width:35%;
margin:2rem auto;
display:block;
color:#fff;
outline:none;
cursor:pointer;
}
</style>
</head>
<body>
<h1>DOM Input number readOnly property Demo</h1>
<p>Hi, Select your day of birth?</p>
<input type="number" class="numberInput">
<button onclick="rFunction()" class="btn">Read Only</button>
<button onclick="rWFunction()" class="btn">Read & Write</button>
<script>
function rFunction() {
var monthInput = document.querySelector(".numberInput");
monthInput.readOnly =true;
}
function rWFunction(){
var monthInput = document.querySelector(".numberInput");
monthInput.readOnly =false;
}
</script>
</body>
</html>실행 결과
위 코드를 실행하면 다음과 같은 화면이 출력됩니다 −

“Read Only” 버튼을 클릭하면 입력 필드가 읽기 전용으로 전환되어 더 이상 값을 수정할 수 없습니다.

이후 “Read & Write” 버튼을 클릭하면 읽기 전용 상태가 해제되어 다시 값을 자유롭게 입력할 수 있습니다. 두 버튼을 번갈아 클릭해 보면 readOnly 속성이 동작하는 방식을 쉽게 이해할 수 있습니다.
