Fragmented Thought

Limiting Textarea Length

By

Published

Lance Gliser

Heads up! This content is more than six months old. Take some time to verify everything still works as expected.

I thought I'd share a sort of plug and play solution to text area length controls that I've been abusing. All credit here goes to Roy Jin, the original developer. I just thought I'd share what a good tool it was, and the $(document).ready() code you need to be up and running. You can pick up the jQuery Textarea Counter on his site, as well as look up docs for tweaking things.

$(document).ready()

$("textarea[maxlength]").each(function (index) { try { var maxLength = $(this).attr("maxlength"); if (maxLength === undefined) { return; } $(this).textareaCount({ maxCharacterSize: maxLength, originalStyle: "originalDisplayInfo", warningStyle: "warningDisplayInfo", warningNumber: 40, displayFormat: "#input Characters | #left Characters Left | #words Words", }); } catch (exception) {} });

Styling

It's actually handy include a css tricks. Naturally, you'll want to adjust the alignment as you desire. I just think it looks nice to the right. The min and max width's are a trick to help you keep the div it creates the same width as the textarea it's tied to. When the plugin fires, it determines what width it should be, and puts that inline. But this makes it keep the accurate width when the browser changes size instead.

div.charleft { text-align: right; max-width: 100%; min-width: 100%; }