Skip to content Skip to sidebar Skip to footer

How Can I Truncate The Contents Of A Textarea Using Javascript?

I have a text field, I am using onkeypress to check the length of the entered string. If it exceeds n number of characters it will return false and it will not accept any other cha

Solution 1:

Try this, if you are using textarea

<textarea onkeypress="return limitlength(this, 20)" style="width: 300px; height: 90px"></textarea>

 function limitlength(obj, length){
    var maxlength=length
    if (obj.value.length>maxlength)
     obj.value=obj.value.substring(0, maxlength)
 }

Solution 2:

Use simple HTML5, no need javascript:

<inputtype="text" maxlength="5"/>

MDN

Solution 3:

Check the length of the entered text in Onkeyup event. If it is greter than n then use substring to truncate first n characters and then set the new string as the value

   $("#mytxt").onkeyup(function(){

 var Currentlength =$(this).val().length;
 var CurrentVal = $(this).val();
 if(Currentlength > n)
 {
  $(this).val(CurrentVal.substring(0,n));
  returnfalse;
 } 
});

Post a Comment for "How Can I Truncate The Contents Of A Textarea Using Javascript?"