To give a textarea field a maxlength, we can simply use the maxlength attribute in HTML.

Let’s see an example below.


In this simple example, we will have a form with a textarea that we simply set to have a maxlength of 50 characters. We do this by adding a maxlength property to the textarea.

Here is our form to try out. Put in an address and try to add more characters to get it over 50.

Code Output:






Full Code:





Set the Textarea Maxlength Using JavaScript

We can also set the maxlength of a textarea using JavaScript. To do this, we simply need to use the getElementById() method and target the maxLength property.

document.getElementById("textarea1").maxLength = 10;

Let’s see this in a simple example.

Here is a simple form:





Change maxlength of the textarea above to 10 characters

For our JavaScript code, we will simply target the id of the textarea, clear any text we have in there, and then set the new maxlength.

We will use an onclick event to call the function setNewMaxlength() which we will create below.

Here is the JavaScript code:

function setNewMaxlength(){
  document.getElementById("textarea1").value = "";
  document.getElementById("textarea1").maxLength = 10;
};

The final code and output for this example are below:

Code Output:




Change maxlength of the textarea above to 10 characters

Full Code:





Hopefully this article has been useful for you to learn how to give a textarea maxlength.

Categorized in:

HTML,

Last Update: March 22, 2024