Dec 13, 2016

Character Limit using JQuery in SharePoint

In this post, we will learn how to implement Character Count (here in this example, maximum allowed 2000 characters) using JQuery in SharePoint.

Prerequisite:
1. Create a SharePoint List with a column named "Comments" - data type Multi line text with plain text as the option selected
2. SharePoint Designer 2013 for editing the SharePoint list with span and to identify the ID of the field created

Solution:
1. Open the SP site in SharePoint designer, navigate to the list -> Create a custom new form -> Edit it.
To know how to create a custom new form in SharePoint Designer, read this article.
2. Below is the HTML code for my "Comments field in SharePoint Designer:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<tr>
    <td width="190px" valign="top" class="ms-formlabel">
        <H3 class="ms-standardheader">
   <nobr>Enter your comment:</nobr>
  </H3>
    </td>
    <td valign="top" class="ms-formbody" style="background-color:#ffffff; width:400px;">
        <SharePoint:FormField runat="server" id="ff6{$Pos}" ControlMode="New" FieldName="Comments" __designer:bind="{ddwrt:DataBind('i',concat('ff6',$Pos),'Value','ValueChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@Comments')}" />
        <SharePoint:FieldDescription runat="server" id="ff6description{$Pos}" FieldName="Comments" ControlMode="New" />
        <span title="2000" id="commentsCount">2000</span><span> Characters Left</span>
    </td>
</tr>
Make a note that I have added a Span tag below the SharePoint control to display the Characters. Also, we have declared it as 2000 characters for this example.
Now, add a script tag or a separate file (then refer it inline) -> add the below code in it save it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
$(document).ready(function() {
 //Character count for comments text
 $("textarea[name*='ff6']").keyup(function () {
  characterCount('ff6', '#commentsCount');
 });
});

//Character count for multiline text 
function characterCount(controlID,spanId)
{
  var controlVal = $("textarea[name*='" + controlID + "']");
  var cmax = $(spanId).attr("title");
  if(controlVal.val().length >= cmax) {
      controlVal.val(controlVal.val().substr(0, cmax));
   }
  $(spanId).text(cmax - controlVal.val().length);            
}
In this above JS, "ff6" is the ID of the SharePoint control.
Save the form and JS, try typing inside the control you can see the characters been automatically counted and decreases as you type. Cool Isn't it? 😉
Please share this post by clicking the below social buttons if this helps you😎
Happy coding! 

2 comments:

Dear Readers,

I LOVE to hear from you! Your feedback is always appreciated. I will try to reply to your query as soon as possible.

1. Make sure to click the "Notify me" check box at the right side to be notified of follow up comments and replies.
2. Please Do Not Spam - Spam comments will be deleted immediately upon review.