I have an text input for pagination page changing. I need to limit typing of page numbers to some number f.e. 15 (max pages number). So i'm trying with this code below but always when number is higher than 15 value is changing to 15 and actual typing number.
actual.on('keypress', function() {
console.log('test');
var t = $(this);
if (t.val() < 1) t.val('1');
if (t.val() > 15) t.val('15');
});
Fiddle: http://jsfiddle.net/v6fhobr7/
Can anybody help?
Try changing it from 'keypress' to 'keyup' ... there's a slight flicker, but it works.
Use a number field.
<input type="number" min="1" max="15" step="1">
#rfornal's solution works okay, but it's hard to type single digit value unless you're really fast:
http://jsfiddle.net/v6fhobr7/7/
So it's better to set a slight timeout before changing the value:
var actual = $('.actual');
var tm;
actual.on('keyup', function () {
var t = $(this);
if (tm) clearTimeout(tm);
tm = setTimeout(function() {
if (t.val() < 1) t.val('1');
if (t.val() > 15) t.val('15');
}, 250);
});
JSFiddle demo: http://jsfiddle.net/v6fhobr7/10/
In jQuery 2.x, you can use actual.on('input'), which does what you want without the flicker.
Note that this will prevent the user from clearing out the input entirely; if you want to allow this then you might want to handle the case where t.val() == '' explicitly.
actual.on('input', function(e) {
var t = $(this);
if (t.val() == '') return;
if (t.val() < 1) t.val('1');
if (t.val() > 15) t.val('15');
});
http://jsfiddle.net/v6fhobr7/12/
Edit:
Note that this solution doesn't restrict input to only numeric characters (you can still type letters and symbols). If you want to prevent that, use this solution in addition to my answer above.
Or, if you don't care about IE 9 or mobile browsers, Mathletics's answer is the best.
Related
i tried to count and limit the user inputs from two text fields. that means max char is 20, then user can enter only 20 char in both text fields.I tried like this
$(document).ready( function() {
jQuery.fn.getLength = function(){
var count = 0;
var max=$("#max").val();
this.each(function(){
count += jQuery(this).val().length;
});
var rem=max-count;
return rem;
};
var $inputs= jQuery('#left,#right');
$inputs.bind('keyup',function(){
var remain=$inputs.getLength();
jQuery('#count').html($inputs.getLength());
$("#left").keyup(function(){
if($("#left").val().length > remain){
$("#left").val($("#left").val().substr(0, remain));
}
});
$("#right").keyup(function(){
if($("#right").val().length > remain){
$("#right").val($("#right").val().substr(0, remain));
}
});
});
});
but it only works for single text box, doesn't take values from 2 fields. any help please..
All you need is this code, it detects the keypress in either #left or #right, if the count of the two is more than 20, it removes the last character typed
$("#left,#right").keyup(function () {
var charCount = $('#left').val().length + $('#right').val().length;
if (charCount > 20) {
difference = -Math.abs(charCount - 20);
$(this).val($(this).val().slice(0, difference));
}
});
Demo http://jsfiddle.net/k8nMY/
My first solution worked on keydown and used return false to stop further entry, however this had the effect of disabling backspace and other keys.
This solution, which executes on keyup waits until after the key is pressed then counts characters. If the number is over 20 it will remove the last character typed. This way, the user can still press backspace and make changes as they wish, but not go over 20 chars.
I have also modified the script further, what it does is detect ANY change, e.g. a paste of a long string. It removes the 'difference' above 20 characters.
This should be a complete solution to the problem.
DEMO: http://jsfiddle.net/EEbuJ/2/
JQuery
$('#left, #right').keyup(function(e) {
if (maxLen() <= 20)
{
// Save the value in a custom data attribute
$(this).data('val', $(this).val());
} else {
// over-ride value with saved data
$(this).val($(this).data('val'));
}
});
function maxLen() {
var x = 0;
$('#left, #right').each(function() {
x += $(this).val().length;
});
return x;
};
This will save the typed in value for your inputs to a custom data attribute, if the total number of characters in the specified inputs is no more than 20.
When the maximum number of characters is reached then we stop saving the typed in value and revert the value back to our previous save (i.e. less than the maxiumum) effectively undo-ing the value.
Well it should be easy one: http://jsfiddle.net/4DETE/1/
var textLength =$inputs.eq(0).val().length+$inputs.eq(1).val().length;
if(textLength>=20)
return false
just count length of values, if you'll have more elements to limit, use jquery.each to iterate inputs
I doubt you can do $inputs.getLength() as $inputs is an array and thus will return the arraylength: 2
You will have to add up the overall sign length in both inputs:
$('#left,#right').keydown(function(){
var leftlength = $('#left').val().length;
var rightlength = $('#right').val().length;
if(leftlength + rightlength > 20)
{
return false;
}
});
or to make it shorter
if($('#left').val().length+$('#right').val().length >20){return false;}
in my project have a jQuery Mobile textarea called "topic" on one page
I have this script I am using to count the characters entered in the textarea, but this script just gives me a result on the first keystroke. the other does not.
$(document).delegate("#topicDialog", "pageinit", function() {
$("#topic").keyup(function(e) {
var tam = $(this).length;
if (tam <= 61700){
$("#maxCarac").html(tam +" typed characters. The maximum allowed is 61700");
} else {
alert("You have reached the maximum text size.\nPlease break your text into more than one topic.");
$("#topic").val($("#topic").substring(61700));
}
});
});
example in action
What can be happening?
you need to use val().length
check the update fiddle here
$("#topic").keyup(function(e) {
var tam = parseInt($(this).val().length);
if (tam <= 61700){
$("#maxCarac").html(tam +" typed characters. The maximum allowed is 61700");
} else {
alert("You have reached the maximum text size.\nPlease break your text into more than one topic.");
$("#topic").val($("#topic").substring(61700));
}
});
http://jsfiddle.net/manishkumarshr/zdEzk/1/
this line needs to be changed
var tam = $(this).val().length;
See Demo
You are retrieving incorrectly the length of the user input. Use this:
var tam = $(this).val().length;
Here a working demo.
I have an editable div and iFrame. I require that the user must not be able to type more than 100 characters per line. The user can enter infinite number of lines all having maximum 100 characters.
Also the user can go back to any line, using arrow keys and enter more text in case that line had less that 100 characters.
How to perform this?
EDIT:
This needs to be like in real time as the user types.
$('#mydivid').keypress(function(e){
if($(this).html().length > 20)
e.preventDefault();
})
Fiddle
you can check with jquery keyup event.
$('DIV ID').keyup(function(){
data = $.trim($('DIV ID')).html().length;
if(data > 100) // or add condition as per your requirement
{
}
else
{
alert('Your message')
}
});
$(document).ready(function(){
var max_length = 100;
$("#div-editable").keypress(function(){
var return_state = true;
$(this).find("div").each(function(){
if($(this).text().length >= max_length)
{
return_state = false;
//break;
}
});
return return_state;
});
});
Just change max_length to your needs.
Also you can use Trim if you want to allow spacing on start and end of the text.
You can check this on jsFiddle
My Requirement is to validate the ip ranges, I need to create a JavaScript function to accept only numeric and it must allow only between the range 0 to 255. If anything is entered beyond that it must alert a message.
I am currently using this below function
<script language="JavaScript">
function allownums(a)
{
if(a <48 ||a > 57)
alert("invalid")
else
alert("vaild")
}
</script>
<input type='text' id='numonly' onkeypress='allownums(event.keycode)'>
I am new to JavaScript, Need some experts suggestion to fix my requirement. Please suggest me
Thanks
Sudhir
Currently you have the test
(a < 48) || (a > 57)
for invalid values. So I would change those:
(a < 0 ) || (a > 255)
You may also need to consider what you'll do with non-integral input like 2.3 - either round it or treat it as invalid.
At present, as Kelvin Mackay points out, you are performing the validation on the keypress event rather than the input value, so change the onkeypress to allownums(this.value).
I would advise changing the alert to a warning in a div, and using the validation to enable/disable a submit button, as popups are quite annoying in just about every circumstance.
To clear the input when an invalid entry is made (as requested in a comment) would make it rather annoying for the user; as soon as a key is pressed to add a digit and make the input invalid, the whole input is cleared. The code, however, would be:
if(!validnum(this.value))
this.value="";
in the input tag, thus:
<input type='text' id='numonly'
onkeyup='if(!validnum(this.value)) this.value="";'>
with the function changed to:
function validnum(a) {
if(a < 0 || a > 255)
return false;
else
return true;
}
or more succinctly:
function validnum(a) {
return ((a >= 0) && (a <= 255));
}
Edit: To alert and clear the box, if you must:
function validOrPunchTheUser(inputElement) {
if(!validnum(inputElement.value)) {
window.alert('badness'); // punch the user
inputElement.value = ""; // take away their things
}
}
<input type='text' id='numonly'
onkeyup='validOrPunchTheUser(this)'>
However, reading other answers, apparently you are looking to validate an octet (e.g. in an IP address). If so, please state that in the question, as it passed me by today. For an octet:
function validateIPKeyPress(event) {
var key = event.keyCode;
var currentvalue = event.target.value;
if(key < 96 || key > 105)
{
event.preventDefault();
window.alert('pain');
return false;
}
else if(currentvalue.length > 2 ||
(currentvalue.length == 2 &&
key > 101)) {
window.alert('of death');
event.preventDefault();
event.target.value = event.target.value.substring(0,2);
}
else
return true;
}
With the input tag:
<input type='text' id='octet'
onkeydown='validateIPKeyPress(event)'>
Except please don't use alerts. If you take out the alert lines, it will silently prevent invalid inputs. Note the change to use onkeydown now, so that we can catch invalid key presses and prevent the value changing at all. If you must clear the input, then do if(!validateIPKeyPress(event)) this.value = "";.
I would rather go instantly for validation of whole ip address. Allowing input both numbers and dots, parsing them thru REGEX pattern.
Pattern usage example you could fetch here:
http://www.darian-brown.com/validate-ip-addresses-javascript-and-php-example/
The code itself would look something like:
<input type='text' id='numonly' value="" onkeypress='allowIp(event)' onkeyup='javascript:checkIp()'>
function allowIp(e){
if((e.keyCode < 48 || e.keyCode > 57) && e.keyCode != 46) // both nubmer range and period allowed, otherwise prevent.
{
e.preventDefault();
}
}
function checkIp()
{
var ip = $("#numonly").val();
/* The regular expression pattern */
var pattern = new RegExp("^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.)(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.)(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.)([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$");
/* use javascript's test() function to execute the regular expression and then store the result - which is either true or false */
var bValidIP = pattern.test(ip);
if(bValidIP){
// IP has ok pattern
$("#numonly").css("background", "green");
}
else {
$("#numonly").css("background", "red");
}
}
You could check it here on fiddle
http://jsfiddle.net/Indias/P3Uwg/
Single Integer
You can use the following solution to check if the user input for a single integer is between 0 - 255:
document.getElementById('example').addEventListener('input', event => {
const input = event.target.value;
console.log(/^\d+$/.test(input) && input > -1 && input < 256);
});
<input id="example" type="text" placeholder="Enter single integer" />
IP Address
Alternatively, you can use the code below to verify that each section of an IP address is between 0 - 255:
document.getElementById('example').addEventListener('input', event => {
const input = event.target.value;
console.log(input === new Uint8ClampedArray(input.split('.')).join('.'));
});
<input id="example" type="text" placeholder="Enter IP address" />
You need to validate the current value of the input, rather than the last key that was pressed:
<input type='text' id='numonly' onkeypress='allownums(this.value)'>
Your function then just needs to be modified to: if(a < 0 || a > 255)
A function like this should do it:
function allownums(value){
var num = parseInt(value,10);
if(num <0 || num>255)
alert('invalid')
}
Then have your html look like:
<input type='text' id='numonly' onblur='allownums(this.value)'>
Live example: http://jsfiddle.net/USL3E/
Update
I've set up a fiddle that does some basic IP-formatting and checks weather or not all input is in range (0 - 255) etc... feel free to use it, improve it, study it... I've also updated the code snippet here to match the fiddle
There are several things you're not taking into account. First and foremost is that not all browsers have a keycode property set on the event objects. You're better off passing the entire event object to the function, and deal with X-browser issues there. Secondly, you're checking key after key, but at no point are you checking the actual value that your input field is getting. There are a few more things, like the use of the onkeypress html attribute (which I don't really like to see used), and the undefined return value, but that would take us a little too far... here's what I suggest - HTML:
<input type='text' id='numonly' onkeypress='allowNums(event)'>
JS:
function allowNums(e)
{
var key = e.keycode || e.which;//X-browser
var allow = '.0123456789';//string the allowed chars:
var matches,element = e.target || e.srcElement;
if (String.fromCharCode(key).length === 0)
{
return e;
}
if (allow.indexOf(String.fromCharCode(key)) === 0)
{//dot
element.value = element.value.replace(/[0-9]+$/,function(group)
{
return ('000' + group).substr(-3);
});
return e;
}
if (allow.indexOf(String.fromCharCode(key)) > -1)
{
matches = (element.value.replace(/\./g) + String.fromCharCode(key)).match(/[0-9]{1,3}/g);
if (+(matches[matches.length -1]) <= 255)
{
element.value = matches.join('.');
}
}
e.returnValue = false;
e.cancelBubble = true;
if (e.preventDefault)
{
e.preventDefault();
e.stopPropagation();
}
}
Now this code still needs a lot of work, this is just to get you going, and hopefully encourage you to look into the event object, how JS event handlers work and all the rest. BTW, since you're new to JS, this site is worth a bookmark
function fun_key()
{
var key=event.keyCode;
if(key>=48 && key<=57)
{
return true;
}
else
{
return false;
alert("please enter only number");
}
}
and you can call this function on keypress event like:
<asp:textbox id="txtphonenumber" runat="server" onkeypress="return fun_key()"> </asp"textbox>
I've seen many answers that have overlooked two important factors that may fail to validate range number on keypress:
When the value in input textbox is NOT SELECTED, the real outcome should be (input.value * 10) + parseInt(e.key) and not simply input.value + parseInt(e.key). It should be * 10 because you add one more digit at the back during keypress, e.g. 10 becomes 109.
When the value in input textbox IS SELECTED, you can simply check if Number.isInteger(parseInt(e.key)) because when 255 is selected, pressing 9 will not turn into 2559 but 9 instead.
So first of all, write a simple function that check if the input value is selected by the user:
function isTextSelected (input) {
if (!input instanceof HTMLInputElement) {
throw new Error("Invalid argument type: 'input'. Object type must be HTMLInputElement.");
};
return document.getSelection().toString() != "" && input === document.activeElement;
}
Next, this will be your on keypress event handler that takes into consideration of the above two factors:
$("input[type='number']").on("keypress", function (e) {
if (!Number.isInteger(parseInt(e.key)) || (($(this).val() * 10) + parseInt(e.key) > 255
&& !isTextSelected($(this)[0]))) {
e.preventDefault();
};
});
Take note of this condition within another brackets, it is one whole condition by itself:
(($(this).val() * 10) + parseInt(e.key) > 255 && !isTextSelected($(this)[0]))
For the < 0 condition, you don't even need it here because the negative sign (-) will be automatically prevented as the sign itself is not an integer.
KNOWN ISSUE: The above solution, however, does not solve the situation when the user move the cursor to the start position of 29 and press 1, which will become 129. This is because 29 * 10 = 290, which already exceed 255, preventing user from entering 129, which is valid. The start position is particularly hard to track when the input type="number". But it should be enough to resolve the normal way of input for an integer range field. Any other better solutions are welcome.
I would like to have some functionality by which if I write
<textarea maxlength="50"></textarea>
<textarea maxlength="150"></textarea>
<textarea maxlength="250"></textarea>
it will automatically impose the maxlength on the textArea. If possible please do not provide the solution in jQuery.
Note: This can be done if I do something like this:
<textarea onkeypress="return imposeMaxLength(event, this, 110);" rows="4" cols="50">
function imposeMaxLength(Event, Object, MaxLen)
{
return (Object.value.length <= MaxLen)||(Event.keyCode == 8 ||Event.keyCode==46||(Event.keyCode>=35&&Event.keyCode<=40))
}
Copied from What is the best way to emulate an HTML input “maxlength” attribute on an HTML textarea?
But the point is I don't want to write onKeyPress and onKeyUp every time I declare a textArea.
window.onload = function() {
var txts = document.getElementsByTagName('TEXTAREA');
for(var i = 0, l = txts.length; i < l; i++) {
if(/^[0-9]+$/.test(txts[i].getAttribute("maxlength"))) {
var func = function() {
var len = parseInt(this.getAttribute("maxlength"), 10);
if(this.value.length > len) {
alert('Maximum length exceeded: ' + len);
this.value = this.value.substr(0, len);
return false;
}
}
txts[i].onkeyup = func;
txts[i].onblur = func;
}
};
}
I know you want to avoid jQuery, but as the solution requires JavaScript, this solution (using jQuery 1.4) is the most consise and robust.
Inspired by, but an improvement over Dana Woodman's answer:
Changes from that answer are: Simplified and more generic, using jQuery.live and also not setting val if length is OK (leads to working arrow-keys in IE, and noticable speedup in IE):
// Get all textareas that have a "maxlength" property. Now, and when later adding HTML using jQuery-scripting:
$('textarea[maxlength]').live('keyup blur', function() {
// Store the maxlength and value of the field.
var maxlength = $(this).attr('maxlength');
var val = $(this).val();
// Trim the field if it has content over the maxlength.
if (val.length > maxlength) {
$(this).val(val.slice(0, maxlength));
}
});
EDIT: Updated version for jQuery 1.7+, using on instead of live
// Get all textareas that have a "maxlength" property. Now, and when later adding HTML using jQuery-scripting:
$('textarea[maxlength]').on('keyup blur', function() {
// Store the maxlength and value of the field.
var maxlength = $(this).attr('maxlength');
var val = $(this).val();
// Trim the field if it has content over the maxlength.
if (val.length > maxlength) {
$(this).val(val.slice(0, maxlength));
}
});
Update Use Eirik's solution using .live() instead as it is a bit more robust.
Even though you wanted a solution that wasn't using jQuery, I thought I'd add one in for anyone finding this page via Google and looking for a jQuery-esque solution:
$(function() {
// Get all textareas that have a "maxlength" property.
$('textarea[maxlength]').each(function() {
// Store the jQuery object to be more efficient...
var $textarea = $(this);
// Store the maxlength and value of the field.
var maxlength = $textarea.attr('maxlength');
var val = $textarea.val();
// Trim the field if it has content over the maxlength.
$textarea.val(val.slice(0, maxlength));
// Bind the trimming behavior to the "keyup" event.
$textarea.bind('keyup', function() {
$textarea.val($textarea.val().slice(0, maxlength));
});
});
});
Hope that is useful to you Googlers out there...
HTML5 adds a maxlength attribute to the textarea element, like so:
<!DOCTYPE html>
<html>
<body>
<form action="processForm.php" action="post">
<label for="story">Tell me your story:</label><br>
<textarea id="story" maxlength="100"></textarea>
<input type="submit" value="Submit">
</form>
</body>
</html>
This is currently supported in Chrome 13, FF 5, and Safari 5. Not surprisingly, this is not supported in IE 9. (Tested on Win 7)
This solution avoids the issue in IE where the last character is removed when a character in the middle of the text is added. It also works fine with other browsers.
$("textarea[maxlength]").keydown( function(e) {
var key = e.which; // backspace = 8, delete = 46, arrows = 37,38,39,40
if ( ( key >= 37 && key <= 40 ) || key == 8 || key == 46 ) return;
return $(this).val().length < $(this).attr( "maxlength" );
});
My form validation then deals with any issues where the user may have pasted (only seems to be a problem in IE) text exceeding the maximum length of the textarea.
This is some tweaked code I've just been using on my site. It is improved to display the number of remaining characters to the user.
(Sorry again to OP who requested no jQuery. But seriously, who doesn't use jQuery these days?)
$(function() {
// Get all textareas that have a "maxlength" property.
$("textarea[maxlength]").each(function() {
// Store the jQuery object to be more efficient...
var $textarea = $(this);
// Store the maxlength and value of the field
var maxlength = $textarea.attr("maxlength");
// Add a DIV to display remaining characters to user
$textarea.after($("<div>").addClass("charsRemaining"));
// Bind the trimming behavior to the "keyup" & "blur" events (to handle mouse-based paste)
$textarea.on("keyup blur", function(event) {
// Fix OS-specific line-returns to do an accurate count
var val = $textarea.val().replace(/\r\n|\r|\n/g, "\r\n").slice(0, maxlength);
$textarea.val(val);
// Display updated count to user
$textarea.next(".charsRemaining").html(maxlength - val.length + " characters remaining");
}).trigger("blur");
});
});
Has NOT been tested with international multi-byte characters, so I'm not sure how it works with those exactly.
Also add the following event to deal with pasting into the textarea:
...
txts[i].onkeyup = function() {
...
}
txts[i].paste = function() {
var len = parseInt(this.getAttribute("maxlength"), 10);
if (this.value.length + window.clipboardData.getData("Text").length > len) {
alert('Maximum length exceeded: ' + len);
this.value = this.value.substr(0, len);
return false;
}
}
...
The maxlength attribute is supported in Internet Explorer 10, Firefox, Chrome, and Safari.
Note: The maxlength attribute of the <textarea> tag is not supported in Internet Explorer 9 and earlier versions, or in Opera.
from HTML maxlength Attribute w3schools.com
For IE8 or earlier versions you have to use the following
//only call this function in IE
function maxLengthLimit($textarea){
var maxlength = parseInt($textarea.attr("maxlength"));
//in IE7,maxlength attribute can't be got,I don't know why...
if($.browser.version=="7.0"){
maxlength = parseInt($textarea.attr("length"));
}
$textarea.bind("keyup blur",function(){
if(this.value.length>maxlength){
this.value=this.value.substr(0,maxlength);
}
});
}
P.S.
The maxlength attribute of the <input> tag is supported in all major browsers.
from HTML maxlength Attribute w3schools.com
You can use jQuery to make it easy and clear
JSFiddle DEMO
<textarea id="ta" max="10"></textarea>
<script>
$("#ta").keypress(function(e){
var k = e.which==0 ? e.keyCode : e.which;
//alert(k);
if(k==8 || k==37 || k==39 || k==46) return true;
var text = $(this).val();
var maxlength = $(this).attr("max");
if(text.length >= maxlength) {
return false;
}
return true;
});
</script>
It is tested in Firefox, Google Chrome and Opera
Better Solution compared to trimming the value of the textarea.
$('textarea[maxlength]').live('keypress', function(e) {
var maxlength = $(this).attr('maxlength');
var val = $(this).val();
if (val.length > maxlength) {
return false;
}
});
Small problem with code above is that val() does not trigger change() event, so if you using backbone.js (or another frameworks for model binding), model won't be updated.
I'm posting the solution worked great for me.
$(function () {
$(document).on('keyup', '.ie8 textarea[maxlength], .ie9 textarea[maxlength]', function (e) {
var maxLength = $(this).attr('maxlength');
if (e.keyCode > 47 && $(this).val().length >= maxLength) {
$(this).val($(this).val().substring(0, maxLength)).trigger('change');
}
return true;
});
});
I implemented maxlength behaviour on textarea recently, and run into problem described in this question: Chrome counts characters wrong in textarea with maxlength attribute.
So all implementations listed here will work little buggy. To solve this issue I add .replace(/(\r\n|\n|\r)/g, "11") before .length. And kept it in mind when cuting string.
I ended with something like this:
var maxlength = el.attr("maxlength");
var val = el.val();
var length = val.length;
var realLength = val.replace(/(\r\n|\n|\r)/g, "11").length;
if (realLength > maxlength) {
el.val(val.slice(0, maxlength - (realLength - length)));
}
Don't sure if it solves problem completely, but it works for me for now.
Try this jQuery which works in IE9, FF, Chrome and provides a countdown to users:
$("#comments").bind("keyup keydown", function() {
var max = 500;
var value = $(this).val();
var left = max - value.length;
if(left < 0) {
$(this).val( value.slice(0, left) );
left = 0;
}
$("#charcount").text(left);
});
<textarea id="comments" onkeyup="ismaxlength(this,500)"></textarea>
<span class="max-char-limit"><span id="charcount">500</span> characters left</span>
Try to use this code example:
$("#TextAreaID1").bind('input propertychange', function () {
var maxLength = 4000;
if ($(this).val().length > maxLength) {
$(this).val($(this).val().substring(0, maxLength));
}
});
2022 Update
You can set the HTML attribute for "maxlength" with the property maxLength (note the uppercase L). You might end up on this page if you were trying to use maxlength (all lowercase) and it wasn't working.
textareaElement1.maxLength = 50;
textareaElement2.maxLength = 150;
textareaElement3.maxLength = 250;
If you wanted to programmatically do it to all existing textareas, you could just iterate over a getElementsByTagName result:
const textAreas = document.getElementsByTagName('textarea');
for (const element of textAreas) {
element.maxLength = 150;
}
This is much easier:
<textarea onKeyPress="return ( this.value.length < 1000 );"></textarea>