Limit all text fields to the specified number of characters

The page has a text area number. The dynamic number is not fixed. I need to limit the length of all text areas on one page. How to do this in js or jquery?


My attempt: -

<body> <div id="contact"> <form action="" method="post"> <fieldset> <table style="width: 100%;"> <tr class="questionsView" style="width: 100%;margin: 5px;"> <td class="mandatory"> <b>1&nbsp; *Qywerew we</b> <hr/> <table class="profileTable" style="margin-left: 25px;"> <tr> <td> <textarea style="border: solid 1px #800000;" rows="5" name="165" cols="100"> </textarea> </td> </tr> </table> </td> </tr> <tr> <td> &nbsp; </td> </tr> <tr class="questionsView" style="width: 100%;margin: 5px;"> <td class=""> <b>2&nbsp; a da da da</b> <hr/> <table class="profileTable" style="margin-left: 25px;"> <tr> <td> <textarea style="border: solid 1px #800000;" rows="5" name="166" cols="100"> </textarea> </td> </tr> </table> </td> </tr> <tr> <td> &nbsp; </td> </tr> </table> <input type="submit" value="Submit" onclick="return checkThis()"> </fieldset> </form> </div> <script> $('textarea').bind('paste keyup blur', function(){ $(this).val(function(i, val){ return val.substr(0, 5); }); }); </script> </body> 
+4
source share
3 answers
 $('textarea').bind('paste keyup blur', function() { $(this).val(function(i, val) { return val.substr(0, 5); }); }); 

jsFiddle .

Update

I don't know why, but it prints function(i, val) { return val.substr(0, 5); } function(i, val) { return val.substr(0, 5); } in the text area every time.

It looks like you are using an older version of jQuery (pre 1.4 ). The recovered code below will work.

 $('textarea').bind('paste keyup blur', function() { $(this).val(this.value.substr(0, 5)); }); 

jsFiddle .

The previous code would not work until jQuery 1.4, because it only expected the string as an argument to val() . Passing a function, its toString() was implicitly called, returning a string representation of the function.

+3
source

Horrible and aggressive way

 setInterval(function(){ $('textarea').each(function(){ if (this.value.length > 5){ this.value = this.value.substr(0,5); } }) }, 1) 

http://jsfiddle.net/YMsEF/

0
source
 var maxLettersCount = 3; $('textarea').bind('keydown paste', function(event) { var textarea = $(event.target), text = textarea.val(), exceptionList = { 8: true, 37: true, 38: true, 39: true, 40: true, 46: true }; if (event.type == 'keydown' && text.length >= maxLettersCount && !exceptionList[event.keyCode]) { return false; } else if (event.type == 'paste') { setTimeout(function() { textarea.val(textarea.val().substring(0, maxLettersCount)); }, 1); } }) 
-1
source

All Articles