Computer >> 컴퓨터 >  >> 프로그래밍 >> HTML

HTML DOM Textarea maxLength 속성 – 사용법과 예제 총정리

HTML DOM의 Textarea maxLength 속성은 HTML 문서 내 텍스트 영역(textarea) 요소의 maxLength 속성값을 읽어오거나 수정할 때 사용됩니다. 이 속성을 활용하면 사용자가 입력할 수 있는 최대 글자 수를 자바스크립트로 동적으로 확인하거나 변경할 수 있습니다.

문법(Syntax)

maxLength 속성의 기본 문법은 다음과 같습니다.

1. maxLength 값 가져오기

object.maxLength

2. maxLength 값 설정하기

object.maxLength = "number"

이제 HTML DOM Textarea maxLength 속성의 실제 사용 예제를 살펴보겠습니다.

예제(Example)

<!DOCTYPE html>
<html>
<style>
    body {
        color: #000;
        height: 100vh;
    }
    .btn {
        background: #db133a;
        border: none;
        height: 2rem;
        border-radius: 2px;
        width: 40%;
        display: block;
        color: #fff;
        outline: none;
        cursor: pointer;
    }
    .show {
        font-size: 1.5rem;
        margin: 1rem 0;
    }
</style>
<body>
<h1>DOM Textarea maxLength Property Demo</h1>
<textarea maxlength="50">Hi! I'm a text area element with some dummy text.</textarea>
<button onclick="set()" class="btn">Show Maximum Length</button>
<div class="show"></div>
<script>
    function set() {
        document.querySelector('.show').innerHTML = 'The maximum number of characters allowed in the above text area is ' + document.querySelector("textarea").maxLength;
    }
</script>
</body>
</html>

실행 결과(Output)

HTML DOM Textarea maxLength 속성 – 사용법과 예제 총정리

위 코드를 실행한 후 “Show Maximum Length” 버튼을 클릭하면, 해당 textarea 요소에 설정된 maxLength 속성값이 화면에 표시됩니다.

HTML DOM Textarea maxLength 속성 – 사용법과 예제 총정리

정리

maxLength 속성은 폼 유효성 검사나 사용자 입력 제한 기능을 구현할 때 매우 유용합니다. HTML에서 maxlength 어트리뷰트로 초기값을 지정할 수 있으며, 자바스크립트의 DOM 접근을 통해 런타임 중에도 값을 자유롭게 읽고 변경할 수 있다는 점이 핵심입니다.