tags:

views:

56

answers:

2

Hi Everyone,

I am wondering if it is possible to limit the amount of characters in an element with a specified class using jQuery?

For instance, the following elements with the class shortened would only show 40 or so characters.

<p class="shortened">This would be the text limited to 40 Characters</p>

Thanks in advance for all your help.

+3  A: 

Perhaps a plugin?

http://plugins.jquery.com/project/TrimText

Depending on your needs this may be easy or hard. Truncating simple text is easy, truncating html is slightly harder, and if you want to truncate html and have an expand button to put the text back, that's harder yet.

Mark
Thanks Mark! I will use a plugin if I have to but would interested in hearing any other ideas you may have.
pixelflips
@pixelflips, I suggest using a plugin, because later on you might find that your text is too complex for a 5 liner script.
Mark
+3  A: 

For <input type="text" /> elements, you can just use the maxlength attribute.

For other elements, such as <textarea>, you can check on the element's onkeyup event.

$('.shortened')
    .keyup(function(e){
        var $this = $(this);
        $this.text($this.text().substring(0, max)); //Set max to 40, or whatever you want
    });

For other, non-form elements, you can do the same thing, but you don't have to do it on an event handler.

$('.shortened')
    .each(function(){ 
        var remainTxt = $(this).text().substring(max, $(this).text().length);
        $(this).text($(this).text().substring(0,max));
    });

Edit: To match up with Mark's answer, you can store the remaining .text() substring and append that when the user clicks on an "expand" button.

Michal
Yeah, substring should be able to take care of this easily, but probably every instance of .`val()` in the second snippet you mean `.text()` right.
Mark