Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Textarea maxlength check

Textarea validation,

How to limit the characters in a textarea for not exceeding more than 50 characters.

<textarea rows="5" cols="15"></textarea>

Thanks.....

like image 304
Hulk Avatar asked Dec 06 '25 08:12

Hulk


2 Answers

Using:

<textarea rows="5" cols="15" maxlength="50"></textarea>

From http://sigswitch.com/2008/07/textarea-maxlength-with-jquery/:

  $(document).ready(function(){
     $('textarea[maxlength]').keyup(function(){
      var max = parseInt($(this).attr(’maxlength’));
      if($(this).val().length > max){
       $(this).val($(this).val().substr(0, $(this).attr('maxlength')));
      }

      $(this).parent().find('.charsRemaining').html('You have ' + (max - $(this).val().length) + ' characters remaining');
     });
    });
like image 107
zaf Avatar answered Dec 08 '25 20:12

zaf


One Google away.

<script language="javascript" type="text/javascript">
<!--
function imposeMaxLength(Object, MaxLen)
{
  return (Object.value.length <= MaxLen);
}
-->
</script>

Implementation:
<textarea name="myName" onkeypress="return imposeMaxLength(this, 50);" ></textarea> 

EDIT:

Code that doesn't freeze text:

<script type="text/javascript">

/***********************************************
* Textarea Maxlength script- © Dynamic Drive (www.dynamicdrive.com)
* This notice must stay intact for legal use.
* Visit http://www.dynamicdrive.com/ for full source code
***********************************************/

function imposeMaxLength(obj) {
        const mlength = obj.getAttribute ? parseInt(obj.getAttribute("maxlength")) : ""
        if (obj.getAttribute && obj.value.length > mlength) {
            obj.value = obj.value.substring(0, mlength)
        }
        obj.value = obj.value.trim()
    }

</script>

<textarea maxlength="40" onkeyup="return imposeMaxLength(this)"></textarea>
like image 32
Marcus L Avatar answered Dec 08 '25 21:12

Marcus L



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!