HTML Textbox Form – Character Limit

May 6, 2012Category: Tutorial, WebTags: ,

Last semester CESAC moved our registration system for the Career Fair to an online version run by Purdue Conferences. There were issues.

One big one was that the company description box said it was limited to 400 words. In reality, it was limited to 300 characters. Which is way too small. So we’re working with Conferences to try and fix that.

Meanwhile I’m working on automating the member database for the Council so that the next webmaster has less code to touch. I’ve got the List page done, the quick edits working, and I’m almost finished building the New Member page. One feature of the page will be a text box for inputting a description for the member.

I decided, one thing that would be useful would be a live updating ticker on the side of the box, giving the user an up to date character number, so they know how much more can be added. Up to date to the point of every keystroke.

How to do this though, is the question. I Googled to see if anyone else had built one, and couldn’t find anything. So I just started working on my own from scratch. The first thing was how to grab the value of characters. The second would be how to update the page. And the third would be how to trigger those events on each keystroke.

First part was easy enough, it’s just .val().length, added to the text box. The second part was also easy, I used .text(), which replaces just the inside text of an element without having the replace the entire thing. The third was tricky though.

I considered using .keydown(), but that triggers on any key, not just value keys, and if you press and hold down a key, it only triggers once, not each time the letter/number is added to the box. .keypress() though, ended up being exactly what I was looking for. The final code was remarkably simple for what it does.

$(document).ready(function(){
    $(“.new_description”).keypress(function(event) {
        window.setTimeout(function(){ $(“.new_textlength”).text( $(“.new_description”).val().length + “/1000″ ); }, 1);
    });
});

Note there is a setTimeout in there as well. I tried it without that, but the number updated before registering the changed value of characters, so it would be one off. The setTimeout fixed the problem.