DOM(Documnet Object Model)
웹화면을 구성하는 html을 쉽게 접근할 수 있도록 해주는 모델
document.getElementbyId('').value; : 특정 id의 요소를 불러오는 코드
console.log(''); : 콘솔창에 출력하는 코드
<script>
var content = document.getElementById('jasoseol').value;
console.log(content);
</script>
.length : 문자열의 길이
<body class="container">
<h1>자기소개</h1>
<textarea class="form-control" rows="3" id="jasoseol">저는 인성 문제가 없습니다.</textarea>
<script>
var content = document.getElementById('jasoseol').value;
console.log(content.length);
</script>
</body>
document.getElementById('count').innerHTML = 내용; ID가 count인 요소에 내용을 입력
<body class="container">
<h1>자기소개</h1>
<textarea class="form-control" rows="3" id="jasoseol">저는 인성 문제가 없습니다.</textarea>
<span id="count">(0/200)</span>
<script>
var content = document.getElementById('jasoseol').value;
document.getElementById('count').innerHTML = '(' + content.length + '/200)';
</script>
</body>
함수 정의
function 함수이름() {
명령어;
}
함수 호출
함수이름();
<body class="container">
<h1>자기소개</h1>
<textarea class="form-control" rows="3" id="jasoseol">저는 인성 문제가 없습니다.</textarea>
<span id="count">(0/200)</span>
<script>
function counter() {
var content = document.getElementById('jasoseol').value;
document.getElementById('count').innerHTML = '(' + content.length + '/200)';
}
counter();
</script>
</body>
글자를 쓸 때마다 자동으로 글자수를 세도록 코딩
이벤트 & 이벤트 핸들링
키보드를 누를 때마다 (이벤트 / onkeydown)
글자 수를 세주어라 (이벤트 핸들링 / 'counter();')
textarea에 아래 코드 추가
onkeydown = 'counter();'
<body class="container">
<h1>자기소개</h1>
<textarea onkeydown='counter();' class="form-control" rows="3" id="jasoseol">저는 인성 문제가 없습니다.</textarea>
<span id="count">(0/200)</span>
<script>
function counter() {
var content = document.getElementById('jasoseol').value;
document.getElementById('count').innerHTML = '(' + content.length + '/200)';
}
counter();
</script>
</body>
200자를 넘으면 글을 못 쓰도록 구현하기
.substring(); : 문자열 자르기
.substring(0, 5);: 0이상 5미만 자리까지 자르기
0도 포함되기 때문에 200자까지 쓸 수 있게하려면 .substring(0, 200) 입력
<body class="container">
<h1>자기소개</h1>
<textarea class="form-control" rows="3" id="jasoseol" onkeydown="counter();">저는 인성 문제가 없습니다.</textarea>
<span id="count">(0/200)</span>
<script>
function counter() {
var content = document.getElementById('jasoseol').value;
if(content.length > 200) {
content = content.substring(0, 200);
document.getElementById('jasoseol').value = content;}
document.getElementById('count').innerHTML = '(' + content.length + '/200)';
}
counter();
</script>
</body>