limit character entry with jquery May
18
1
0

It's common to need to limit character count on user input fields. There's a lot of plugins that you can get this to do it for you. However, when possible I like to reduce the amount of third party scripts. The basic concept is pretty simple to follow in JQuery.

Lets say you have HTML like the following:

<div id="limit"></div>

...
<textarea name="comment" cols="40" rows="10" id="comment"></textarea>
...

You can then bind a keypress event that checks the lengh of the value on the input or textarea.

$('#comment').keypress(function() {
    var MAX_CHAR = 140 - 1;

    $('#limit').text('Characters remaining: ' + ((MAX_CHAR + 1) - $(this).attr('value').length));

    // limit entry
    if($(this).attr('value').length > MAX_CHAR) {
        this.value = this.value.substring(0, MAX_CHAR);
    }
});

This script prints out how many characters are left in the <div id="limit"> and limits the user to inputing 140 characters. No plugins necessary.

Limiting input on the front end is only a convenience for the user. If this functionality is important for your application make sure to make the proper checks and sensitization on the backend when processing the form.

Bookmark and Share
blog comments powered by Disqus