1

Topic: Limit the Number of characters entered in the editor

Hi,
I need to limit the number of characters entered . I've tried to set the maxlength of the text area but does not help. Any suggestions ??

2

Re: Limit the Number of characters entered in the editor

Is there no way? No feature in TINYMCE to set character limit? This is nuts. Since tinymce is completely javascript it's impossible to put your own hooks in to limit the characters with javascript or tell people how many characters remaining.

This must be a huge oversight on the developers if there is no value to set character limit...

Otherwise you are forced to POST the data, and have the php script check when posting and then return the user to the page!

3

Re: Limit the Number of characters entered in the editor

Somebody must have a solution. Not one variable in TinyMCE allows you to do this without serious hacks? tongue This makes tinymce the worst wysiwygi , since this features is a must have for any wysiwyg editor. Now it has to be done in post, THEN send then back again if they went over character limit. This won't fit in with any web 2.0 websites at all.

4

Re: Limit the Number of characters entered in the editor

Of course you should do it server-side anyway, you can't rely on client-side input being valid wink

This would be a pretty simple plugin. There's a callback for whenever the content is changed, so you could simply calculate the content length there, and prevent any change to the content if it goes over.

5

Re: Limit the Number of characters entered in the editor

Yes,
There is a handle_event_callback configuration which works fine if I add it but the editor loses  its state when I use this. here is my Code

function onChange_value(keydown) {
    var x=tinyMCE.getContent();
    var regex=/<[^>]*>/gi;
    outputstr=x.replace(regex,"");
    if(outputstr.length > 65){
      alert("The length of your message is "+outputstr.length +" the max num of characters \n allowed for this text Area is 65");
      }
}
tinyMCE.init({
    mode : "exact",
    elements : "MessageContent",
    theme : "advanced",
    width :"450",
    height:"75",
    convert_fonts_to_spans : true,
    cleanup_on_startup : true,
    force_p_newlines : true,
    entities :"",
    cleanup : true,
                handle_event_callback : onChange_value(),
    content_css : "/LO/msgMgr/include/sncu_css.css",
    theme_advanced_buttons1 : "bold,italic,underline,justifyleft,justifycenter,justifyright, justifyfull",
    theme_advanced_buttons2 : "",
    theme_advanced_buttons3 : "",
    theme_advanced_fonts : "Arial=arial",
    theme_advanced_toolbar_location : "top",
    theme_advanced_toolbar_align : "left",
    theme_advanced_path_location : "bottom",
    extended_valid_elements : "a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]"
});


What happens is that when i press any key the javascript fuction onChange_value gets called but if I had selected "BOLD" or "Italic" or any other button it gets unselected. So if I select bold the next char will be bold but it again gets unselected after the function is called.

Do I need to do anything else to fix this ???
Help

Last edited by user_m (2006-04-25 01:29:50)

6

Re: Limit the Number of characters entered in the editor

Has anyone solved this issue? I need to have the character input limited too. Any help appreciated!

7

Re: Limit the Number of characters entered in the editor

user_m wrote:

Yes,
There is a handle_event_callback configuration which works fine if I add it but the editor loses  its state when I use this. here is my Code

function onChange_value(keydown) {
    var x=tinyMCE.getContent();
    var regex=/<[^>]*>/gi;
    outputstr=x.replace(regex,"");
    if(outputstr.length > 65){
      alert("The length of your message is "+outputstr.length +" the max num of characters \n allowed for this text Area is 65");
      }
}

The docs state that the function called by handle_event_callback should[must] return true to continue normal tinyMCE internal processing of events.
Your implementation does not return anything...  Maybe ?

8

Re: Limit the Number of characters entered in the editor

A possible work around is

1) add an additional hidden <div>
<div id="hidden" style="display:none"></div>

2) rather than check for size limit when user type, check it when user submit the form, which is needed especially when user doing copy and paste,

function doSubmit() {
document.getElementById('hidden').innerHTML = tinyMCE.getContent();

var txtLen = document.getElementById('hidden').innerText.length;
if ( txtLen > 1000) {
    alert ('The max length allowed is 1000');
}
}

Last edited by webster (2006-08-18 19:15:00)

9

Re: Limit the Number of characters entered in the editor

Sorry tried your code Webster...
still the same problem...

this is really a big issue...
can 4 the love of god somebody fix this problem
i don't want users to 'after' they submit get an alert
i don't want users to get an alert while typing.
i want what the normal  maxlength="50" would do.
go to the next line.... is this possible ?

please i am sure that evereybody that uses Tiny for frontend use, wants to use this
...........

10

Re: Limit the Number of characters entered in the editor

This is interesting.

11

Re: Limit the Number of characters entered in the editor

this little peace of PHP works 4 me, $message= the textfield
it adss a space what breaks the line
after this peace of PHP do a $message = nl2br($message);
<?
                                $arrWords = explode(' ', $message);
        foreach($arrWords as $key => $word)
        {
        $arrWords[$key] = wordwrap($word, 57, ' ', 1);
        }
        $message = implode(' ', $arrWords);
?>

hope this is usefull to someone, i sure as hell searched the whole internet

12

Re: Limit the Number of characters entered in the editor

I've a textarea.Below to it,I've span element which intially shows "0/4000".

Upon entering characters in textarea,the span element should be updated like ,for 5 characters entered it should "5/4000".

I've tried onkeyup() function,but it's not working under tiny_MCE textarea.

can somebody help on this?

13

Re: Limit the Number of characters entered in the editor

The same problem!

I think developers themselves don't know the solution, so they can't share it with us.

sad

14

Re: Limit the Number of characters entered in the editor

FreshCat wrote:

I think developers themselves don't know the solution, so they can't share it with us.

You're kidding, right?

If you really need to restrict the number of characters, then you'll need a combination of these callbacks: cleanup_callback, handle_event_callback and onchange_callback.

You'll have to make sure that you don't count the HTML code as content characters...

But I must point out that all this isn't reliable input because a user can change your JavaScript easily. So you must check your input on the server side, too.

cusebr wrote:

Of course you should do it server-side anyway, you can't rely on client-side input being valid wink

Greetings from Germany,

Felix Riesterer.

Greetings from Germany,

Felix Riesterer.
(-> about me and this forum <-)

15

Re: Limit the Number of characters entered in the editor

Felix,

It would sure be helpful if you could elaborate a little bit on how to use the callbacks in combination to get a character count from the textarea.  In my case, I would not want to omit the characters for HTML, as I am trying to account for the total number of characters before I do my database insert.

I realize the importance of serverside validation, but from a usability perspective client side validation is much more useful and immediate.

Thanks for any help you can provide.

16

Re: Limit the Number of characters entered in the editor

Hi cbates!

cbates wrote:

It would sure be helpful if you could elaborate a little bit on how to use the callbacks in combination to get a character count from the textarea.

You are familiar with the concept behind TinyMCE's callback functions, right? The manual describes them in a rather short way but one should get the idea.

Why did I mention a combination of different callbacks? It might be useful to warn the user if the maximum of characters is already used up. So the handle_event_callback should fire onkeypress to send the notification whenever this input creates another character which adds to the already reached maximum.

The cleanup_callback is the most important one because it makes sure that only the allowed maximum of characters gets submitted. A notification should come up if the cleanup makes cuts on the submitted data just to inform the user why the submitted input on the server has "losses"...

cbates wrote:

In my case, I would not want to omit the characters for HTML, as I am trying to account for the total number of characters before I do my database insert.

The most tricky and most annoying part will be the use of formatting actions. Let's say that a user wants to turn a word into bold print. This will add additional HTML code and increase the overall number of characters inside the textarea. Here we would need the onchange_callback to make sure that this action doesn't add too many characters to the textarea. But if this leads to a cut at the end of the content then you'll have to make sure that it still produces valid (X)HTML code and doesn't leave any HTML tags open. Of course you will have to warn your user again...

cbates wrote:

I realize the importance of serverside validation, but from a usability perspective client side validation is much more useful and immediate.

Well, yes and no. The client-side validation gives a user a very immediate feedback on what he or she is about to get, but the server-side validation simply is a must-have whereas the client-side validation is nice but optional. If you want your system to be secure you simply cannot leave out the server-side validation!

Greetings from Germany,

Felix Riesterer.

Greetings from Germany,

Felix Riesterer.
(-> about me and this forum <-)

17

Re: Limit the Number of characters entered in the editor

Hi Felix,

Thank you very much for this description.

Could I ask for a JavaScript for Dummies explanation?
Would you be so kind as to put all of the required code into a js that would work?
For instance, my form is named form, and the TinyMCE textfield is named Subtitle.

I'd appreciate that greatly.

Thanks, Cliff

18

Re: Limit the Number of characters entered in the editor

Hi Cliff!

Cliff wrote:

Could I ask for a JavaScript for Dummies explanation?

What part in my description wasn't suitable for "dummies"? If you need basic programming skills then I suggest you try some basic scripts with simple functionalities first... This thing we're discussing here needs a rather sophisticated approach.

Cliff wrote:

Would you be so kind as to put all of the required code into a js that would work?

No, sorry. This would require much more time than I'm willing to give to others freely. This has a dimension where professionals come in to charge you money for doing this for you, and believe me, this task is a worthy task for a regular IT worker and webdeveloper!

I can't afford this amount of time to do your work for you since I'm not a professional web person who could offer you a deal here.

Greetings from Germany,

Felix Riesterer.

Greetings from Germany,

Felix Riesterer.
(-> about me and this forum <-)

19

Re: Limit the Number of characters entered in the editor

Here is a solution that works for me.  It's a bit clunky but gets the job done.  It works for multiple instances of the editor, albeit with the same character limit.  I used a separate function to do the counting so the code could be repurposed in one of the other mentioned event handlers.  I used the timeout as a work around for a bug in FireFox where 'onchange_callback' was getting stuck in a loop.

The code alerts a user that they have exceeded the max limit and changes the editors background pink.  When the user fixes the problem (< limit), it alerts the user that the problem has been fixed and turns the editors background back to white white.

I hope this helps!

Tony



//declare neccessary global variables
var textcounter = new Object, textcounterwarning = new Object,textcountercurrentinst,textcounting_maxcharacters=62600;

function myCustomOnChangeHandler(inst) {
    checknumberofcharacters(inst.getBody().innerHTML.length,inst);
}



function checknumberofcharacters(texttocheck,inst){
        if(textcounter[inst.editorId]){
            textcounter[inst.editorId] = texttocheck;
            if ( textcounter[inst.editorId] >= textcounting_maxcharacters && textcounterwarning[inst.editorId] == false){
                //set background color to red-ish
                inst.getWin().document.body.style.backgroundColor='#F6CECC';
                //set flag that user has been warned
                textcounterwarning[inst.editorId] = true;
                //set temp variable holding editor name for alert
                textcountercurrentinst = inst.editorId;
                setTimeout("alert('Your element has exceeded the '+textcounting_maxcharacters+' character limit.  You are currently using '+textcounter[textcountercurrentinst]+' characters. If you add anymore text it may be truncated when saved.')",2);
            }else if(textcounter[inst.editorId] < textcounting_maxcharacters && textcounterwarning[inst.editorId] == true){
                //set background color to white
                inst.getWin().document.body.style.backgroundColor='#FFFFFF';
                //set flag that warning has been disabled
                textcounterwarning[inst.editorId] = false;
                //set temp variable holding editor name for alert
                textcountercurrentinst = inst.editorId;
                setTimeout("alert('The number of characters in your element has been reduced below the '+textcounting_maxcharacters+' character limit.  You are currently using '+textcounter[textcountercurrentinst]+' characters.')",2);
               
            }
        }else{
            //setup variables
            textcounter[inst.editorId] = texttocheck;
            textcounterwarning[inst.editorId]=false;
            checknumberofcharacters(texttocheck,inst);
            }
}


tinyMCE.init({
....
onchange_callback: "myCustomOnChangeHandler"
});

20

Re: Limit the Number of characters entered in the editor

amutti,

Your code works except one situation, I have modified it to my preferences. If I have limit of 5, then when I add 6 characters. Yes, I got an msg that i have exceeded the limit. But when I remove all the characters, then I added some 6 characters, I am unable to validate the limit anymore.

21

Re: Limit the Number of characters entered in the editor

I played with this exact example and had mixed results.  When I added characters I got the warning that I had exceeded.  When I removed characters I didn't always get the warning that I had decreased the characters below the limit, but clicking the mouse anywhere on the page usually gave me the message.  When it didn't give me the message I checked the source and found 'nbsp; ' or an line return and some spaces in the source that where >= 6.

I think using handle_event_callback and capturing the keypress will give better results, but this was a quick and dirty solution.  Let me know if you make it work any better.

Tony

22

Re: Limit the Number of characters entered in the editor

I don't know if this solution will work for you all, but here's what I did:

First, I created three DIV tags -- one holds the current count, the second holds the maximum allowed and the third contains the text area. I set the max count field to not display, but you could if you wanted to show it.

For example:

<div id="DescCount" style="width:40px;float:left;font-weight:bold;text-align:center"><%=2400-Len(Comments)%></div> 
<div id="DescMax" style="display:none">2400</div> 
<div style="float:left;clear:right"> 
<textarea rows="15" class="textin" id="Desc" name="Comments" tabindex="30" style="width: 600px"><%=Comments%></textarea> 
</div>

Then, in the <head> section, I included the following:

<script type="text/javascript"> 
tinyMCE.init({ 
mode : "exact", 
elements : "Desc", 
theme : "advanced", 
theme_advanced_buttons1 : "fontselect,fontsizeselect,bold,italic,underline,separator,justifyleft,justifycenter,justifyright, justifyfull,separator,hr,code,removeformat,separator,bullist,numlist,separator,undo,redo", 
theme_advanced_buttons2 : "", 
theme_advanced_buttons3 : "", 
theme_advanced_toolbar_location : "top", 
theme_advanced_toolbar_align : "left", 
onchange_callback : "CheckSize", 
handle_event_callback : "CheckSize" 
}); 

function CheckSize() { 
var editor_id=tinyMCE.selectedInstance.formTargetElementId; 
var Limit=document.getElementById(editor_id + 'Max').innerHTML; 
var Show=editor_id + 'Count'; 
var x=tinyMCE.getContent(); 
if (x.length>Limit) { 
x=x.substring(0, Limit-10); 
tinyMCE.setContent(x); 
alert('You have reached the maximum size for this field'); 
}; 
document.getElementById(Show).innerHTML=Limit-x.length; 
return true; 
} 
</script>

This seems to work just fine for me...

Question, though... why do I have to include all this script in the page itself? I'd much rather use an external script page so I didn't have so many lines of code in the actual page. This doesn't work if I move the above code to an external page.

Anyway, since everyone is asking, I thought I'd present my solution.

--Doug

23

Re: Limit the Number of characters entered in the editor

PS:

I forgot to mention...

The different names are coordinating names. The text area is given an ID. Then the div that is going to hold the current count is give an ID that matches, plus the extension of "Count." The div that holds the maximum value is given an ID that matches, plus the extension of "Max." So, in my code, I used a textarea ID of "Desc." Therefore the other two DIV's are set up with ID's of DescCount and DescMax.

You can modify as needed, but I did it this way so I could have any number of text areas on a page and have the counts appear wherever I wanted them to appear without having to change the actual JavaScript.

--Doug

24

Re: Limit the Number of characters entered in the editor

perreault, I like the script in yr post.

25

Re: Limit the Number of characters entered in the editor

I need a word counter (or character counter actually) that has these rules:
1) Real-time count as you type
2) Prevents user typing more than the max limit
3) No pop-up alerts

I came up with the following code. It needs some cleaning up but it works. The trick is to capture the content after every event (like a key press) so if the user goes beyond the max char limit the script replaces the entire content with the last captured content, thus performing an undo on the last event. TinyMCE's undo doesn't record minor events such as a key press, only a major event like a return, so I had to create my own "micro" undo. It's IE6 and FF compatible. Enough wibble, here's the code.

<HTML>
<HEAD>
<SCRIPT language="javascript" type="text/javascript" src="../jscripts/tiny_mce/tiny_mce.js"></SCRIPT>
<SCRIPT language="javascript" type="text/javascript">
    tinyMCE.init({
        mode : "exact",
        elements: "text1",
        theme : "simple",
        handle_event_callback : "myHandleEvent",
        onchange_callback : "myCustomOnChangeHandler",
        oninit : "myCustomOnInit"
    });

var text1_count=0;//init int
var text1_maxchars=200;// max plain text chars allowed
var text1_undobuffer="";//init string

//init when unit TinyMCE editor is loaded
function myCustomOnInit(){
    tinyMCE_timer1=setTimeout("countchars('form1','text1',text1_maxchars,'msgCounter')",1000); //wait a bit to avoid IE error
}

//event when something in TinyMCE changes (which is when an undo level is added. e.g. paste)
function myCustomOnChangeHandler(inst){
    tinyMCE_timer1=setTimeout("countchars('form1','text1',text1_maxchars,'msgCounter')",250); //slight delay before counting
}

//event such as key or mouse press
function myHandleEvent(e){
    //window.status = "event:" + e.type;
    if(e.type=="keyup"){
        clearTimeout(tinyMCE_timer1);
        countchars('form1','text1',text1_maxchars,'msgCounter')
    }
    return true;
}

function getHTML_TinyMCE(txtfield){
    obj=document.getElementById('mce_editor_0');
    if(obj.contentDocument){
        content=obj.contentDocument.body.innerHTML; //FireFox (getContent() messes up cursor position)
    }else{
        content=tinyMCE.getContent(txtfield); //IE
    }
    return content;
}

function stripTags_TinyMCE(txtfield) { //strips html tags leaving plain text
    content=getHTML_TinyMCE(txtfield);
    var re = /(<([^>]+)>)/ig ; //strip all tags
    plaintext = content.replace(re, "");
    return plaintext;
}

function countchars_TinyMCE(txtfield){
    content=stripTags_TinyMCE(txtfield);
    cnt=content.length;
    //alert(cnt);
    return cnt;
}
function countchars(formname,txtfield,maxchars,displayID){
    //editor_id=tinyMCE.selectedInstance.formTargetElementId; // get ID of focused TinyMCE editor
    thefield=eval("document."+formname+"."+txtfield);
    if(isNaN(maxchars)){ //arg could contain a var name rather than a number
        maxchars=eval(maxchars); //convert var to number
    }
    currCount=countchars_TinyMCE(txtfield); // current length of TinyMCE field
    remainCount=maxchars-currCount+1; //fix: allow +1
    tmpvar=txtfield+'_count';   
    eval(tmpvar + '=currCount'); //assign dynamic var to char count
    displayObj=document.getElementById(displayID);
    displayObj.innerHTML="You have " + eval(remainCount-1) + " characters remaining"; //-1 to counteract above +1
    if(remainCount<=0){ //typed too much
        if(text1_undobuffer.length > 0){
            tinyMCE_timer2=setTimeout("tinyMCE.setContent(text1_undobuffer)",250); // undo event - replace content with most recent buffer
        };
        displayObj.innerHTML="<B>You have typed the maximum text allowed</B>";
    } else {
        text1_undobuffer=getHTML_TinyMCE(txtfield); //store content in buffer
    }
}
</SCRIPT>
</HEAD>
<BODY>

<FORM name="form1" method="post" action="">
<TEXTAREA id="text1" name="text1" rows="10" cols="80" style="width: 500px"></TEXTAREA><BR/>
<SPAN id="msgCounter">Maximum of <SCRIPT language="javascript">document.write(text1_maxchars);</SCRIPT> characters allowed</SPAN><BR/>
</FORM>

</BODY>
</HTML>

If anyone improves on it please post your code back here. It doesn't work with multiple instances - it nearly does, just a few tweaks required.

Gary.