[TIL]221209 (HTML/CSS) textarea 글자수 제한

이태은·2022년 12월 11일
0

회고

목록 보기
65/71
post-thumbnail

textarea 글자수 제한 하는 방법

프로젝트에 들어가는 모달창에 내용 입력하는 칸이 필요한데
글자 입력 수를 제한하는걸 해보고싶었당 ㅎㅎㅎㅎㅎㅎ


  • css
 .text_box {
 position:relative; 
 display:inline-block; 
 width:100%;
 }
.text_box textarea {
width:100%; 
height:152px; 
color:#666; 
font-family:"ht_r"; 
font-size:18px; 
line-height:28px; 
padding:20px; 
border:1px solid #e4dcd3; 
outline:0; 
resize:none
}
.text_box .count {
position:absolute; 
right:20px; 
bottom:20px; 
color:#666; 
font-family:"ht_r"; 
font-size:15px;
}

  • html
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<div class="text_box">
  <textarea></textarea>
  <div class="count"><span>0</span>/200</div>
</div>

  • javascript
# 키보다가 눌릴때 { } 안의 함수 실행
$('.text_box textarea').keyup(function(){
  
  # 함수	content는 이 함수 이다.
  var content = $(this).val();
  $('.text_box .count span').html(content.length);
  if (content.length > 200){
    alert("최대 200자까지 입력 가능합니다.");
    $(this).val(content.substring(0, 200));
    $('.text_box .count span').html(200);
  }
});

자바스크립트 뜯어보기

keydown

  • keyboard가 눌렀을때 실행됩니다.

  • keyboard를 눌렀을때 실행되기 때문에 현재 input에 입력되어 있는 값을 가져올 수 없다.

  • keydown은 키보드를 누르고 있으면 계속 함수가 실행됩니다.


keyup은 keyboard에서 손을 땠을때 실행됩니다.

  • keyboard에서 손을 땠을때 실행되기 때문에 현재 input에 입력되어 있는 값을 가져올 수 있다.

  • keyup은 키보드를 계속 누르고 있어도 함수는 실행되지 않습니다.


keypress

  • keyboard가 눌렀을때 실행이 된다. 하지만 현재는 deprecated 된다.

  • keypress 대신에 keydown, keyup을 상황에 맞게 사용하는것이 좋다.

profile
나는 탱구

0개의 댓글