Oneezy
Oneezy

Reputation: 5013

How To: Control character count p tag with contenteditable="true"?

Question:

How to control character count inside a p tag with the new html5 attribute, contenteditable="true" ?


I've found out how to do this with a textarea:
http://jsfiddle.net/timur/47a7A/ (working)

But how would would I do this with a p tag?
http://jsfiddle.net/47a7A/133/ (not working)

HTML

<p id="textarea" maxlength="99" contenteditable="true">This content is editable with a max character count of 99.</p>
<div id="textarea_feedback"></div>

JQUERY

$(document).ready(function() {
    var text_max = 99;
    $('#textarea_feedback').html(text_max + ' characters remaining');

    $('#textarea').keyup(function() {
        var text_length = $('#textarea').val().length;
        var text_remaining = text_max - text_length;

        $('#textarea_feedback').html(text_remaining + ' characters remaining');
    });
});

Upvotes: 0

Views: 2491

Answers (2)

Shukhrat Raimov
Shukhrat Raimov

Reputation: 2247

The problem with @PaulRoub answer is that the caret cursor move to the beginning of the text if it exceeds the limit of characters. I solved this problem using jquery caret plugin. The following code illustrates the limit of 4000 chars for div element with id ="#text_area"

    <script src="~/Scripts/jquery.caret.js"></script>
    <script type="text/javascript">
        var limit = 4000;
        var $chars_left = limit - $('#text_area').text().length;

        $('#char_limit').text($chars_left); //char_limit is span element that is used as a counter
        $('#text_area').on('input', function (e)
        {

            var $char = $('#text_area').text().length;
            $chars_left = limit - $char;
            $('#char_limit').text($chars_left);
            if ($char > 4000)
            {
                var $text = $('#text_area').text().substr(0, 3999);
                $('#char_limit').text(0);
                $('#text_area').html($text);
                $('#text_area').caret(3999); //here is jquery.caret plugin that remain the position of the cursor
            }
        })
</script>

Upvotes: 0

Paul Roub
Paul Roub

Reputation: 36438

<p> elements don't have values. That's for input, textarea, etc.

You want to use text()

$(document).ready(function() {
    var text_max = 99;
    $('#textarea_feedback').html(text_max + ' characters remaining');

    $('#textarea').keyup(function() {
        var text_length = $('#textarea').text().length;
        var text_remaining = text_max - text_length;

        $('#textarea_feedback').html(text_remaining + ' characters remaining');
    });
});

Working example: http://codepen.io/paulroub/pen/Hfymr

Upvotes: 3

Related Questions