1,804 articles and 14,800 comments as of Friday, March 25th, 2011

EndUserSharePoint has combined resources with NothingButSharePoint.com. You can now find End User (Mark Miller), Developer (Jeremy Thake) and IT Pro SharePoint (Joel Oleson) content all in one place!

This site is a historical archive and is no longer being updated. Please update your favorites, bookmarks and RSS feeds.

NothingButSharePoint.com
Friday, April 2, 2010

Add character or word count to SharePoint multi line plain text field and restrict input length

Guest Author: Alexander Bautz
SharePoint JavaScripts

I got this request from Larry:

new request for you. Character/word counter for multiple line field to display below the field. Not general for all multiple lines, but setup in a way that can set fieldinternalnames in am arr. also can we add a character limit, so user can not enterany more text.

I have several character counters. cant get it on the form. I am also looking into adding it on the create field page. calculated fields can only accept about 1000 characters. would like a way to display the count on that page.

I cannot help with the “create new column page”, as it is a server side file, shared between all site collections running on this server.


As always we start like this:

Create a document library to hold your scripts (or a folder on the root created in SharePoint Designer). In this example i have made a document library with a relative URL of “/test/English/Javascript” (a sub site named “test” with a sub site named “English” with a document library named “Javascript”):


The jQuery-library is found here. The pictures and the sourcecode refers to jquery-1.3.2.min. If you download another version, be sure to update the script reference in the sourcecode.

Add this code to a CEWP below the NewForm or EditForm, change the script reference to match your location of jQuery:

<script type="text/javascript" src="../../Javascript/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
fields = init_fields();

counterForMultiLinePlain('MyMultiline',true,50,true,'Remaining words: ');

function counterForMultiLinePlain(FieldInternalName,countWords,limit,colorCodeCounter,counterPrefix){
if(counterPrefix==undefined)counterPrefix='';
	$(fields[FieldInternalName]).find('textarea').keyup(function(e){
		var thisLength = $(this).val().length; // Characters
		if(countWords && thisLength>0){ // Count words
			thisLength = $(this).val().split(/[' '|\n]/).length;
		}
		// Color code
		if(colorCodeCounter && limit>0){
			if(thisLength>(limit-5)){
				$("#myCustomCounter_"+FieldInternalName).css({'background-color':'#FF0000','font-weight':'bold','color':'white'});
			}else if(thisLength>(limit-10)){
				$("#myCustomCounter_"+FieldInternalName).css({'background-color':'#FF6600','font-weight':'bold','color':'white'});
			}else{
				$("#myCustomCounter_"+FieldInternalName).css({'background-color':'transparent','font-weight':'normal','color':'black'});
			}
		}
		// Limit
		if(limit>0){
			if(countWords){ // Count words
				while(thisLength>limit){
					currVal = $(this).val();
					$(this).val(currVal.substring(0,currVal.lastIndexOf(' ')));
					thisLength--;
				}
			}else{ // Count characters
				if(thisLength>limit){
					currVal = $(this).val();
					$(this).val(currVal.substring(0,limit));
				}
			}
			thisLength = (limit-thisLength<0)?0:limit-thisLength;
		}
		$("#myCustomCounter_"+FieldInternalName).html(counterPrefix+thisLength);
	}).parents('td:first').append("<span id='myCustomCounter_"+FieldInternalName+"' style='padding:2;'></span>").find('textarea').keyup();
}

function init_fields(){
var res = {};
$("td.ms-formbody").each(function(){
if($(this).html().indexOf('FieldInternalName="')<0) return;
var start = $(this).html().indexOf('FieldInternalName="')+19;
var stopp = $(this).html().indexOf('FieldType="')-7;
var nm = $(this).html().substring(start,stopp);
res[nm] = this.parentNode;
});
return res;
}
</script>

Parameters explained:

  • FieldInternalName: FieldInternalName of the multi line plain text field.
  • countWords: true to count words, false to count characters.
  • limit: 0 for no limit and count up, a value bigger then 0 to set a limit and to count down.
  • colorCodeCounter: true to add orange/red coding when limit is approaching.
  • counterPrefix: The text to show before the counter.

Read here how to add a CEWP to the NewForm, DispForm or EditForm and how to find the FieldInternalName of your columns.

Ask if anything is unclear
Alexander

This article was originally published on Alexander’s blog SharePoint JavaScripts.

Guest Author: Alexander Bautz
SharePoint JavaScripts

Alexander Bautz is a SharePoint consultant/developer (mainly JavaScript/jQuery solution) living in Norway. Alexander spends a lot of his spare time blogging on the same topics. His focus area is "end user customizations" with no (or as little as possible) server side code.

View all entries in this series: Alexander Bautz»
 

Please Join the Discussion

12 Responses to “Add character or word count to SharePoint multi line plain text field and restrict input length”
  1. Charlie Epes says:

    Hi Alexander:
    Your method of posting solutions on your blog and here (using the “As always we start like this:” approach) is a great model for other developers.

    Oh… and… nice solution, by the way- :-)

    Charlie Epes

  2. darsh says:

    I am not a developer. I have issue while implemeting the above mention code.
    Here is the step which I have followed.
    1) on the site I have created folder javascript and uploaded the jQuery1.4.2.js file
    2) copy the code and change src=”../../Javascript/jquery-1.4.2.min.js”>
    3) create a list name count and created a column named desc with Multiple lines of text.
    4) added cewp and on the source code copy and pasted the above code with changes as jquery-1.4.2.min.js

    Please let me know where I am missing?

    Regards,
    Darsh

  3. S. W. says:

    Planning tweaks to the SP 2010 statusnotes control to show a character countdown a la Twitter. I’m a bit rusty with javascript. I want to allow the countdown to go into the negative range and allow the user to keep typing so he can go back and pick and choose which words to keep. Is this something you’ve looked at doing and could you point me to a recommended way to approach this?

    Thanks in advance, really appreciate the post. I knew it would be easy to have a character countdown and had one in a few minutes using your posts and code.

    Sarah

    • Hi,
      If you are planning om letting the users add “to many words” and then revising the text, you must disable the “OK” button until the users have removed enough words. If not, the “limit” is not worth much.

      Do it like this:

      $("input[id$='SaveItem']").attr('disabled','disabled');
      

      The removing of the excess words happens in line 25-30. You must modify it to allow going into the negative range.

      Alexander

      • S. W. says:

        Fantastic, that worked great.

        I modified as shown below. My count now goes into the negative range, allowing the user to continue typing, but as soon as he goes beyond the limit the OK button is disabled.

        // Limit
        if(limit>0){
        if(countWords){ // Count words
        while(thisLength>limit){
        currVal = $(this).val();
        //$(this).val(currVal.substring(0,currVal.lastIndexOf(’ ‘)));
        //thisLength–;
        $(”input[id$='SaveItem']“).attr(’disabled’,'disabled’);
        }
        }else{ // Count characters
        if(thisLength>limit){
        currVal = $(this).val();
        //$(this).val(currVal.substring(0,limit));
        $(”input[id$='SaveItem']“).attr(’disabled’,'disabled’);
        }
        }
        //thisLength = (limit-thisLength<0)?0:limit-thisLength;
        thisLength = limit-thisLength;
        }

        Thanks so much for the assistance. This is working great, and super simple.

        Sarah

      • Lee says:

        Another wonderful tool for me! Everything just work fine except one situation that I met.

        If the word count reached limit, and the OK button is grey out. Even I reduced the number of words, the OK button will not be undimmed.

        Is there a way to fix this?

  4. animesh says:

    Hi,

    I am having a problem in getting the CEWP just below the multiline field like how you have shown in the screen shot.

    I am able to add the CEWP into the New Item page using the “&toolpaneview=2″ trik. But it comes below the page and not just below the multiline field. Could you please guide me to get the CEWP displayed just below the multiline field, just in the same way how it is there in the screen shot above.

    Thanks in advance.

    Regards,
    Animesh.

    • Animesh,

      I don’t believe you need to add CEWP below the multiline. Since the code has the refernce to the field, this CEWP can be in Web Part Zone right below the main zone.

      Just my 2c

  5. How do I apply this to multiple plain text fields on the same form? Is it possible? I have total of 4 fields on the same newform.aspx and need to do the same for remaining 3 fields.

    How do I place the word “Remaining words: ” right underneath the field it is tied to? Right now it appears above the field.

  6. John Brooks says:

    Does any have the CEWP code to increase the width of a multiline enhanced text box?
    Thanks for your Help.

  7. rachel says:

    If I want to limit the charater to 255, do I just change the code

    counterForMultiLinePlain(’MyMultiline’,true,50,true,’Remaining words: ‘);

    from 50 to 255?

    I tried, but it seems it counts one line as one character. Did I miss anything?


Notify me of comments to this article:


Speak and you will be heard.

We check comments hourly.
If you want a pic to show with your comment, go get a gravatar!