find a location for property in a new city

Thursday, 10 May 2012

Set maxlength on a textarea

It's annoyed me for quite a while that you can set a maximum length on an <input type="text" /> but not on a textarea. Why? Are they so different?

I immediately thought I was going to have to write some messy JavaScript but then I learned that HTML5 implements maxlength on text areas now and I'm only considering modern browsers! Wahoo!

Then I learnt that IE9 doesn't support it so JavaScript it is...

JavaScript textarea maxlength limiter

What I have done that works well is bind events keyup and blur on my text area to a function that removes characters over the maxlength provided. The code looks like this:

$('#txtMessage').bind('keyup blur', function () {
    var $this = $(this);
    var len = $this.val().length;
    var maxlength = $this.attr('maxlength')
    if (maxlength && len > maxlength) {
        $this.val($this.val().slice(0, maxlength));
    }
});

Conclusion

It works quite well because if the browser already supports maxlength on a textarea there will be no interruption because the value of the textarea will not go over that maxlength.

The keyup event doesn't fire when the user pastes text in using the mouse but that is where the blur event comes in. Also, an enter click makes a new line on a textarea so the user has to click the submit button (blurring the textarea).

Beware though that this is for usability only; a nasty user could easily bypass this so ensure you are checking the length server side if it is important to you.

Follow britishdev on Twitter

4 comments:

  1. Hey man was just browsing through the internet looking for some information and came across your blog. I am impressed by the information that you have on this blog. http://scarprin.net/

    ReplyDelete
  2. The post was able to express what it wants to convey to the readers. It has been a very effective approach which resulted to a profitable output for all who have been fortunate enough to come across it! http://celabright.biz

    ReplyDelete
  3. I must also sometimes make such a perfectly website with such good information. I hope your website will still survive for very long. They are wonderful! Thank you!

    For more info click here http://www.scarprin.com/

    ReplyDelete
  4. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from Javascript Training in Chennai . or learn thru JavaScript Online Training India. Nowadays JavaScript has tons of job opportunities on various vertical industry.

    ReplyDelete