728x90
๋ฐ์ํ
๊ธ์์ ๊ณ์ฐ๊ธฐ ๋ง๋ค๊ธฐ with ์๋ฐ์คํฌ๋ฆฝํธ
ํ์์ง์
1. getElementById๋ฅผ ์ด์ฉํด
ใด DOM(Document Object Model)์ id ๊ฐ์ ธ์ค๊ธฐ
2. onkeydown ์ด๋ฒคํธ
HTML ์ฝ๋
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>๊ธ์์ ๊ณ์ฐ๊ธฐ</title>
<style> //์คํ์ผ ์ง์
h1 {
margin-top: 30px; // ์๋จ ๊ณต๊ฐ๊ณผ์ ๊ฑฐ๋ฆฌ
}
#count {
float: right;
}
</style>
</head>
<body class='container'>
<h1>์๊ธฐ์๊ฐ</h1> // ์ ๋ชฉ ์
๋ ฅ
<textarea class="form-control" rows="3" onkeydown = 'counter();' id="wordarea">์
๋ ฅํ์ธ์</textarea>
<span id="count">(0/200)</span>
</body>
</html>
์๋ฐ์คํฌ๋ฆฝํธ ์ฝ๋
<script>
// counter๋ผ๋ ํจ์ ์ ์
function counter() {
// content ๋ณ์ ์ง์
// getElementById(id์
๋ ฅ)
// -> ํน์ id๋ฅผ ๊ฐ์ง DOM(textarea, span ๊ณผ ๊ฐ์ ํน์ ๊ฐ์ฒด๋ฅผ ์๋ฏธํจ)์ ๊ฐ์ ธ์ด
// .value๋ฅผ ๋ถ์ด๋ฉด ๊ทธ ์์ ๋ด์ฉ์ ๊ฐ์ ธ์ด
var content = document.getElementById('wordarea').value;
//count ๋ผ๋ id๋ฅผ ๊ฐ์ง ๊ฐ์ฒด ๋ด์ฉ (0/200) ์ ๊ฐ์ ธ์จ ํ ํ์ฌ ๊ธ์์ ๋ฃ์ด์ฃผ๊ธฐ
document.getElementById('count').innerHTML = '(' + content.length + ' / 200)';
// ๊ธ์์ 200์ด๊ณผ ์ 200์๋ฆฌ๊น์ง๋ง ํ์
if (content.length > 200){
document.getElementById('wordcount').value = content.substring(0, 200);
}
}
counter() //counter ํจ์ ์คํ
</script>
728x90
๋ฐ์ํ