Search code examples
jquerywordpresscomments

Display number of characters in WordPress comments


i used this php code for limit Wordpress comments length in functions.php

add_filter( 'preprocess_comment', 'wpb_preprocess_comment' );

function wpb_preprocess_comment($comment) {
    if ( strlen( $comment['comment_content'] ) > 1400 ) {
        wp_die('Comment is too long. Please keep your comment under 1400 characters.');
    }

How to display number of available characters left to be updated as the user types? It should be some simple text as "1400 characters left" in the corner of field.

Any suggestions welcome.


Solution

  • You could do it like this:

    $(document).ready(function () {
       $("#area").on("keydown", function() {
          let count = $(this).val().length;
          $("#count").html(1400 - count - 1 + " characters left.");
       });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <textarea id="area"></textarea>
    <div id="count">
    </div>