How To: Limit Input Box Characters To Defined Count Using jQuery


Earlier today working on a project , I found one trick which I would like to share. Here is a small code that limit a input box for defined number of characters.

Please take a look on following example:

HTML

1
<input id="myInput" value=""/>

.

Jquery snippet

Assuming we have to limit characters to 20.

1
2
3
4
5
6
7
$(document).ready(function(){	
	$('#myInput').keyup( function() {
		var $this = $(this);
		if($this.val().length > 20)
			$this.val($this.val().substr(0, 20));			
	});
     });

.

That’s it, yeah its done!! You can check Working Demo

Any updations, suggestions and corrections are welcome.



Comments

05.20.11

We dont need to use jquery to limit the chars in an input box. There is ‘maxlength’ property for the input box.

05.20.11

I’ve recently started a blog, the information you provide on this site has helped me tremendously. Thank you for all of your time & work.

05.20.11

Well, the max length property does not work in case of textarea or multiline text box control.

Please visit below link that explains how to limit characters in textarea control.

http://jquerybyexample.blogspot.com/2010/10/set-max-length-for-aspnet-multiline.html

05.20.11

Look at this – don’t is beautiful site? I believe so.
hdt6dsj