Set Max characters in textarea base on Textarea height and width

∥☆過路亽.° 提交于 2021-01-27 20:35:53

问题


Notes: I tried all questions & answers related to this topic.

I want to limit the number of characters Base on Textarea height and width.. suppose I have set Textarea height :50px and width:60px; so i want to prevent character after completed Textarea .

Notes: Set Max characters by Textarea height and width.

Related Search Links

  1. limit-height-of-textarea-based-on-content
  2. textarea-character-limit

.textareaClass {
  height: 50px;
  width: 60px;
  resize: none;
  overflow: hidden
}
<textarea class="textareaClass"></textarea>

回答1:


i created a code looking at howmuch chars fit in the width and height of the textarea and setting the max-lenght of the textarea based on that number

$('.textareaClass').keypress(function(){
	let width = $(this).css('width').replace(/[^-\d\.]/g, ''); //getting the width of textarea
  let height = $(this).css('height').replace(/[^-\d\.]/g, '');//getting the height of textarea
  let widthchar = Math.floor(parseInt(width) / 7.5);//based on the width howmuch characters fit sideways
  let heightchar = Math.floor(parseInt(height) / 15);//based on the height, howmuch lines of characters are there
  let totalchar = widthchar * heightchar; //multiply lines by chars sideways to get a total amount of chars
  $(this).attr('maxlength',totalchar);//setting the total as total for the text area
  $(".char").html('you are allowed to type:'+ totalchar+'character(s)');//output to see howmuch you can type, just for debug/programming reasons to see what's happening
});
.textareaClass {
  height:100px;
  width: 50px;
  resize: none;
  overflow: hidden
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea class="textareaClass"></textarea>
<div class="char">

</div>



回答2:


You can set the height and width property as ch (character) unit. And set maxlength="(width) * (height / line-height)" attribute to textarea.

.textareaClass {
  height: 10ch;
  width: 10ch;
  line-height: 2ch;
  resize: none;
  overflow: hidden
}
<!-- max-length should be 10 (width) * 10 (height) / 2 (line-height) = 10 * 5 = 50 -->
<textarea class="textareaClass" maxlength="50"></textarea>


来源:https://stackoverflow.com/questions/62471371/set-max-characters-in-textarea-base-on-textarea-height-and-width

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!