Web/jQuery
jQuery - 최대 입력타수 기능
leebean
2021. 12. 30. 22:28
최대 입력 타수 기능은 쇼핑몰 혹은 호텔 등에서 한 번쯤 보셨을 기능입니다, 주로 문의사항이나 환불 요청 등에 사용되는 기능인데 프로젝트를 진행하던 중 단순히 문의사항만 있으면 좀 허전하다는 느낌이 있어서 어떤 기능을 추가할까 고민하던 중에 넣기로 한 기능입니다.
github : https://github.com/delight-HK3/input_limit
GitHub - delight-HK3/input_limit: If you input more than a certain amount by limiting the input, you cannot enter it.
If you input more than a certain amount by limiting the input, you cannot enter it. - GitHub - delight-HK3/input_limit: If you input more than a certain amount by limiting the input, you cannot ent...
github.com
(jQuery 파일도 함께 첨부하였습니다.)
HTML
<htm1>
<head>
<meta charset="utf-8">
<!-- input_limit javascript -->
<script src="/js/jquery-3.6.0.js"></script>
<script src="/js/input_limit.js"></script>
</head>
<body>
<textarea id="limit" cols="50" rows="5" style="padding:10px"></textarea>
<p id="limit_count">(0 / 200)</p>
</body>
</htm1>
jQuery
$(document).ready(function(){ // html 파일이 실행되기 전에 실행
$('#limit').on('keyup', function() {
// id값이 limit를 가지고 있는 태그에 입력이 되었을 경우에 실행
$('#limit_count').html("("+$(this).val().length+" / 200)");
// id값이 limit_count 가지고있는 태그에 limit의 value 값의 길이를 출력
if($(this).val().length > 200) { // limit의 value 값이 길이가 200을 넘긴 경우에 실행
$(this).val($(this).val().substring(0, 200));
// limit의 value 값은 substring을 통해 0 ~ 200까지 index를 지정
// 다시 말하면 200타를 넘어가면 무조건 200번째까지만 입력이 된다는 의미
$('#limit_count').html("(200 / 200)");
// 200 타를 채웠다는 의미로 ( 200 / 200 ) 을 출력
}
});
});