ADD MAXIMUM LENGTH AND COUNTER TO CKEDITOR (FCKEDITOR)


/ Published in: JavaScript
Save to your folder(s)

Adds a functioning counter and maxlength to fckeditor textareas


Copy this code and paste it in your HTML
  1. //jQuery load function
  2. $(window).load(function() {
  3. CKEDITOR.replace( 'doc_desc',
  4. {
  5. toolbar :[['Source'],['Cut','Copy','Paste','PasteText','SpellChecker'],['Undo','Redo','-','SelectAll','RemoveFormat'],[ 'Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink' ], ['SpecialChar','PageBreak']]
  6. });
  7. function textCounter2(field, countfield, maxlimit)
  8. {
  9. if (field.value.length > maxlimit) // if too long...trim it!
  10. field.value=field.value.substring(0, maxlimit);
  11. else // otherwise, update counter
  12. countfield.value=field.value.length;
  13. }
  14. var editor = CKEDITOR.instances.doc_desc;
  15. editor.on( 'key', function( evt ){
  16. // Update the counter with text length of editor HTML output.
  17. textCounter2( { value : evt.editor.getData() },this.form.grLenght2, 500 );
  18. }, editor.element.$ );
  19. // Whether content has exceeded the maximum characters.
  20. var locked;
  21. editor.on( 'key', function( evt ){
  22.  
  23. var currentLength = editor.getData().length,
  24. maximumLength = 500;
  25. if( currentLength >= maximumLength )
  26. {
  27. if ( !locked )
  28. {
  29. // Record the last legal content.
  30. editor.fire( 'saveSnapshot' ), locked = 1;
  31. // Cancel the keystroke.
  32. evt.cancel();
  33. }
  34. else
  35. // Check after this key has effected.
  36. setTimeout( function()
  37. {
  38. // Rollback the illegal one.
  39. if( editor.getData().length > maximumLength )
  40. editor.execCommand( 'undo' );
  41. else
  42. locked = 0;
  43. }, 0 );
  44. }
  45. });
  46. });
  47.  
  48. //textarea input
  49. <textarea name="doc_desc" cols="55" rows="3" class="indexTextNormal" id="doc_desc" onkeydown="textCounter2(this.form.doc_desc,this.form.grLenght2,500);" onkeyup="textCounter2(this.form.doc_desc,this.form.grLenght2,500);"></textarea>
  50. <p>Length: <input readonly="readonly" type="text" name="grLenght2" size="3" maxlength="3" value="0" /> (maximum <b>500</b> characters)</p>

URL: http://romza.com/counter.html

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.