To give a textarea field a maxlength, we can simply use the maxlength attribute in HTML.
<textarea maxlength="100"></textarea>
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:
<form>
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"><br><br>
<label for="lname">Address:</label>
<textarea maxlength="50"></textarea>
<button type="submit" value="Submit">Submit</button>
</form>
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:
<form>
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"><br><br>
<label for="lname">Address:</label>
<textarea id="textarea1"></textarea>
<div id="click-me" onclick="setNewMaxlength()">Change maxlength of the textarea above to 10 characters</div>
</form>
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:
Full Code:
<form>
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"><br><br>
<label for="lname">Address:</label>
<textarea maxlength="50"></textarea>
<button type="submit" value="Submit">Submit</button>
</form>
<script>
function setNewMaxlength(){
document.getElementById("textarea1").value = "";
document.getElementById("textarea1").maxLength = 10;
};
</script>
Hopefully this article has been useful for you to learn how to give a textarea maxlength.
Leave a Reply