If you have used Twitter, then you know that you are only allowed to type 140 characters in a single Tweet. There is a nice little number below the text field indicating how much is left to write.
It would be nice to have this feature for WordPress comments too. Or any text field, for that matter. It can be done with the following piece of JavaScript:
jQuery(function($) { // configure var comment_input = $( '#commentform textarea' ); var submit_button = $( '#commentform .form-submit' ); var comment_limit_chars = 1000; // stop editing here // display how many characters are left $( '' + comment_limit_chars + ' characters left' ).insertAfter( comment_input ); comment_input.bind( 'keyup', function() { // calculate characters left var comment_length = $(this).val().length; var chars_left = comment_limit_chars - comment_length; // display characters left $( '.comment_limit_info span' ).html( chars_left ); // hide submit button if too many chars were used if (submit_button) ( chars_left < 0 ) ? submit_button.hide() : submit_button.show(); }); });
https://gist.github.com/1422754
The first three var
s below the // configure
comment can be edited.
comment_input
is the DOM element of the text field.
submit_button
is the DOM element for the button to submit the form.
Finally, comment_limit_chars
is the amount of characters allowed.
This snippet automatically inserts a div
tag below the text field and updates the character count when the user types. The submit_button
is optional. Set the var
to null
if you don't want it to be grayed out.
Please keep in mind that this only validates the input on the client side. If you have to rely on the maximum text length, like Twitter does, you need to check the length on the back end side with PHP too.
Guest Post
This post is written by Eric Teubert - www.satoripress.com and is a post in our Advent Calendar on WP Engineer about WordPress.
Thank you very much from my part to Eric.
If you also like to have your interesting post published on our website, please let us know on our contact page. Of course we will appreciate your contribution!