This is how you can use jQuery to limit characters inside a textarea. It is a function to set the maximum length of characters for any page element. You could use it to create excerpts for posts on your blog for example. See more jQuery .each Examples.

Demo

(function($) { 
	// jQuery function to set a maximum length or characters for a page element it can handle mutiple elements
        $.fn.createExcerpts = function(elems,length,more_txt) {
		$.each($(elems), function() { 
			var item_html = $(this).html(); //
			item_html = item_html.replace(/< /?[^>]+>/gi, ''); //replace html tags
			item_html = jQuery.trim(item_html);  //trim whitespace
			$(this).html(item_html.substring(0,length)+more_txt);  //update the html on page
		});
		return this; //allow jQuery chaining 
	}
})(jQuery); 

And this is how you use it:

//example call
$().createExcerpts('.blogpost',280,'...'); 
Sam Deering Sam Deering
Sam Deering is a Front-end Web Developer who specialises in JavaScript & jQuery. Sam is driven and passionate about sharing his knowledge to educate others.
  • John Blackshaw

    Wow, this exactly what I’ve looking for! Thank you very much for this =)

  • http://www.roniwahyu.com roniwahyu

    Great! thanks… it’s helpfully

  • rich

    is there way this can work on an element which contains html elements such as images etc and text. I want to use the code to limit characters on blog posts output by a cms but there maybe images in the div I dont want removed which this code dosent account for or work as is?

  • meiti

    tnx. BUT …

    yes it works fine on texts with length more than given arg properly, but works on texts with length less than given arg too ! and that’s wrong.
    would you plz fix it as I’m not familiar with js?

    tnx!

  • Hunor

    Thanks. It works for me…

  • http://janbiasi.ch/ Jan R. Biasi

    Throws a syntax error in my case “unexpected character ^” in your regex…

Stay ahead of the game Exclusive content for developers and digital experts Go Premium