Skip to content Skip to sidebar Skip to footer

Set Max Characters In Textarea Base On Textarea Height And Width

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 :5

Solution 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 textarealet height = $(this).css('height').replace(/[^-\d\.]/g, '');//getting the height of textarealet widthchar = Math.floor(parseInt(width) / 7.5);//based on the width howmuch characters fit sidewayslet heightchar = Math.floor(parseInt(height) / 15);//based on the height, howmuch lines of characters are therelet 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
}
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><textareaclass="textareaClass"></textarea><divclass="char"></div>

Solution 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 --><textareaclass="textareaClass"maxlength="50"></textarea>

Post a Comment for "Set Max Characters In Textarea Base On Textarea Height And Width"