开发者

Limit Characters jquery

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

F开发者_运维技巧or 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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜