Skip Navigation

[Resolved] Limiting characters in post content field

This support ticket is created 3 years ago. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Sun Mon Tue Wed Thu Fri Sat
- 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 -
- 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 -

Supporter timezone: Asia/Hong_Kong (GMT+08:00)

This topic contains 8 replies, has 2 voices.

Last updated by heatherR-2 2 years, 12 months ago.

Assisted by: Luo Yang.

Author
Posts
#2294683

Tell us what you are trying to do?

I'm attempting to limit the number of characters that users can submit in the post content field using a CRED form.

This is the support ticket I'm referencing, but I can't get the code to work for me.

https://toolset.com/forums/topic/limiting-characters-in-field/

This is the link to the page with the CRED form on it:

hidden link

The Coaching Philosophy field is what will submit as the post content field once the user submits the form.

Below are the contents of my JS editor for this form. The relevant section of code for this ticket is everything below the comment ''Validate maximum characters in post_content field."

jQuery(document).ready(function ($) {

// Limit to selection of 5 niches in a coach listing.
var niche_limit = 5;

$('input:checkbox[name="niche[]"]').on('change', function(evt) {

if($('[name="niche[]"]:checked').length > niche_limit) {

this.checked = false;
alert("Maximum 5 niches allowed.")

}
});

});

// Validate maximum characters in post_content field
jQuery(document).ready(function ($) {

$('[name^=post_content]').attr('maxlength',280);

});

( function( $ ) {
$( document ).ready( function(){

// insert div to display char count
$('textarea[name="post_content"]').after("<div class='char-count'>0</div>");

// listen for keyup and update the count
$('textarea[name="post_content"]').keyup( function(){

var chars = $('textarea[name="post_content"]').val().length;

$('.char-count').html( chars );
});
});
})( jQuery );

#2295175

Hello,

The post body field of Toolset post form is using WordPress Tinymce editor, which is different from post excerpt field, you can use below JS codes to send some message to user when they input too much words, for example:

document.addEventListener('DOMContentLoaded', function(event) {
    window.tinyMCE.on( 'AddEditor' , function( event ) {
        var editor = event.editor;
  
        if( editor.id.endsWith( 'post_content' ) ) {
            var editor_id = editor.id; // tinyMCE ID
            editor.on( 'change', function() {
                    var getContent = editor.getContent();         // gets the Content of the active editor
                    var count= getContent.split(" ").length;
                    if(count > 10){ // replace 10 with the word count limitation
                       alert( 'Too much words: ' + count );
                    }
            } )
        }
    } );
});
#2296027

Excellent! Thank you. A few follow-up questions:

1. Is it possible to edit this to count characters instead of words?

2. Is it possible to output the character count after the tinyMCE field, instead of having an alert if there are too many characters? That is, the character count will count up visually as the user types. That way they always know how many characters they have left.

3. Is it possible to limit the maximum number of characters in the tinyMCE field, so the user cannot type any more characters even if they try after hitting the max number?

Thanks for your help!

#2296243

Please try below JS codes:

document.addEventListener('DOMContentLoaded', function(event) {
    window.tinyMCE.on( 'AddEditor' , function( event ) {
        var editor = event.editor;
   
        if( editor.id.endsWith( 'post_content' ) ) {
            var editor_id = editor.id; // tinyMCE ID
            editor.on( 'setcontent beforeaddundo keyup', function(e) {
              	var count = editor.getContent({format:"raw"}).replace(/<.[^<>]*?>/g,
"").replace(/&[^;]+;/g,"?").length;
              	jQuery('.character-count').html('character count: ' + count);
              	if(count > 10){ // replace 10 with the word count limitation
                   alert('Too much input!');
              	}
            })
        }
    } );
});

and add a HTML div tag after the post body field:

<div class="character-count"></div>
#2296909

Thank you very much! This works very well.

My last question is if it's possible to trim any letters that the user tries to type past the character count, and delete those trimmed letters from the field.

Or in some other way validate the field contents so the user cannot submit the form if characters are above the maximum character count.

I ask this because with the current solution if a user happens to paste in content that's longer than the maximum number of allowed characters, it's still possible for them to submit the form if they simply click "OK" to make the alert go away.

Appreciate your continued help!

#2298311

Please try below JS codes:

document.addEventListener('DOMContentLoaded', function(event) {
    window.tinyMCE.on( 'AddEditor' , function( event ) {
        var editor = event.editor;
   
        if( editor.id.endsWith( 'post_content' ) ) {
            var editor_id = editor.id; // tinyMCE ID
            editor.on( 'BeforeSetContent', function(e) {
              	var count = e.content.replace(/<.[^<>]*?>/g,
"").replace(/&[^;]+;/g,"?").length;
              	if(count > 10){ // replace 10 with the character count limitation
                  e.preventDefault();
              	}
            })
            editor.on( 'setcontent beforeaddundo keyup', function(e) {
                var count = editor.getContent({format:"raw"}).replace(/<.[^<>]*?>/g,
"").replace(/&[^;]+;/g,"?").length;
                jQuery('.character-count').html('character count: ' + count);
                if(count > 10){ // replace 10 with the word count limitation
                   alert('Too much input!');
                }
            })
        }
    } );
});
#2299487

Hmm, it's still not quite executing in a user-friendly way. Here's a quick 1-min Loom showing what might work instead:

hidden link

I appreciate your help!

#2299525

There isn't such kind of built-in feature within Toolset plugins, it is only an example for your reference, for example you can modify the JS codes as below:

document.addEventListener('DOMContentLoaded', function(event) {
    window.tinyMCE.on( 'AddEditor' , function( event ) {
        var editor = event.editor;
   
        if( editor.id.endsWith( 'post_content' ) ) {
            var editor_id = editor.id; // tinyMCE ID
            editor.on( 'BeforeSetContent keydown', function(e) {
                var count = editor.getContent({format:"raw"}).replace(/<.[^<>]*?>/g,
"").replace(/&[^;]+;/g,"?").length;
              	jQuery('.character-count').html('character count: ' + count);
              	if(count > 10){ // replace 10 with the character count limitation
                  tinyMCE.activeEditor.undoManager.undo();
                  e.preventDefault();
                  alert('Too much input!');
              	}
            }) 
        }
    } );
});

If you don't want to the alert message, you can remove this line from above codes:
alert('Too much input!');

#2300591

Hm, gotcha. I'll continue to tinker with this until it's working how I need it to. I appreciate your help!