Limit the length of an input with JQuery

For instances where a textbox/textarea need to be limited to a specific number of characters, one way of achieving this is with a bit of JQuery. Simply give the input a class (in this case, “maxThirtyCharacters”) and set a “maxChars” variable to the appropriate number. There will be tidier ways of doing this, which you can adapt to your specific situation, but the very basic version goes a little like this;

    $(".maxThirtyChars").keyup(function() {
        var maxChars = 30;
        if ($(this).val().length > maxChars) {
            $(this).val($(this).val().substr(0, maxChars));
            //Take action, alert or whatever suits
            alert("This field can take a maximum of 30 characters");

remember to also check server side though.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s