js
[jQuery] textarea ๊ธ์ ์ count / keyup event
natrue
2021. 5. 17. 14:25
728x90
keypress event | ์ ๋ ฅํ ์ ์๋ ํค๋ณด๋๋ฅผ ๋๋ ์๋ ์คํ (ํ๊ธ x, ์๋ฌธ o) |
keyup event | ๋๋ฅธ ํค์์ ์์ ๋ ๋ ์คํ. |
keydown event | ํค๋ณด๋์ ์ด๋ ํ ํค๊ฐ ๋๋ ค๋ ์คํ |
textarea ๊ธ์ ์๋ฅผ count ํ๊ธฐ์ํด์ keyup event ์ฌ์ฉ.
<!DOCTYPE html>
<html>
<head>
<style>
.wrap {
width: 300px;
height: auto;
position: relative;
display: inline-block;
}
.wrap textarea {
width: 100%;
resize: none;
min-height: 4.5em;
line-height:1.6em;
max-height: 9em;
}
.wrap span {
position: absolute;
bottom: 5px;
right: 5px;
}
#counter {
background:rgba(255,0,0,0.5);
border-radius: 0.5em;
padding: 0 .5em 0 .5em;
font-size: 0.75em;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(function() {
$('#content').keyup(function (e){
var content = $(this).val();
// CSS์ ๊ธธ์ด ๋จ์ ์ค em๊ณผ rem์ ์๋์ ์ผ๋ก ํฌ๊ธฐ๋ฅผ ์ ํ๋ค.
$(this).height(((content.split('\n').length + 1) * 1.5) + 'em');
$('#counter').html(content.length + '/600');
});
$('#content').keyup(); // ์ฒ์ ์ธํ
});
</script>
</head>
<body>
<div class="wrap">
<textarea id="content" maxlength="300"></textarea>
<span id="counter"></span>
</div>
</body>
</html>

