ItSolutionStuff.com

How to Set Maxlength for Textarea in Javascript?

By Hardik Savani • June 26, 2023
Javascript HTML

Today, i was planing to post something like regarding to javascript. I was thinking what post should i add and i plan to make maxlength validation with display remaining character count using javascript. So you can simply make character limit with remaining counter in javascript.

Here, i am going to make very simple example to do this, you don't require to import jquery. You have to just write following javascript code. So I used onkeyup and onkeydown event of code javascript.

It would be easy to use using onkeydown and onkeyup event and make it character count validation in html. So let's just see bellow example and copy that code. You will get fresh example.

Example:

<!DOCTYPE html>

<html>

<head>

<title>How to set maxlength for textarea in javascript?</title>

</head>

<body>


<div class="container">


<form>

<textarea name="message" placeholder="Write Here..." onkeydown="limitTextOnKeyUpDown(this.form.message,this.form.countdown,160);" onkeyup='limitTextOnKeyUpDown(this.form.message,this.form.countdown,160);'></textarea>

You have

<input readonly type="text" name="countdown" size="3" value="160"> chars are left

</form>


</div>


<script type="text/javascript">

function limitTextOnKeyUpDown(limitField, limitCount, limitNum) {

if (limitField.value.length > limitNum) {

limitField.value = limitField.value.substring(0, limitNum);

} else {

limitCount.value = limitNum - limitField.value.length;

}

}

</script>


</body>

</html>

I hope it can help you....

Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

How to Convert Object to String in Javascript?

Read Now →

Javascript Convert Array into Comma Separated String Example

Read Now →

How to Check Array Is Empty Or Null In Javascript?

Read Now →

How to Generate Random String in Javascript?

Read Now →

How to Get First Element of Array in Javascript?

Read Now →

How to Get Last Element of Array in Javascript?

Read Now →

How to Get Max Attribute Value in JQuery?

Read Now →

How to Remove Query String from URL using JQuery?

Read Now →

Automatically Scroll to Bottom of Div JQuery Example

Read Now →

Check and Uncheck All Checkbox using JQuery Example

Read Now →

How to Allow Only One Checkbox Checked at a Time in JQuery?

Read Now →

How to Convert Line Breaks to br in jQuery ?

Read Now →

How to Check Object is Empty or Not in JQuery?

Read Now →

Autocomplete with Images and Custom HTML Code in Jquery UI?

Read Now →