ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming»
  • Programming Languages

Javascript: Controlling the number of characters entered into a HTML form field.

Updated on September 11, 2012

Allowing a certain number of characters submitted

Have you ever needed to keep up with the number of characters passed or submitted in a HTML form field from a user. Or, have you ever wanted to give the user a better online experience by visually showing the user the number or percentage of text they have keyed in, or both. I use the following javascript sample to stop potential problems before the user submits the html form.

This javascript will display a bar graph showing the percentage used based on the number of characters you want to allow the user to submit.

The below javascript needs to be placed between the <HEAD></HEAD> tags of your document.


<script type="text/JavaScript">
function textCounter(field,counter,maxlimit,linecounter) {
	// text width//
	var fieldWidth =  parseInt(field.offsetWidth);
	var charcnt = field.value.length;        
	// trim the extra text
	if (charcnt > maxlimit) { 
		field.value = field.value.substring(0, maxlimit);
	else { 
	// progress bar percentage
	var percentage = parseInt(100 - (( maxlimit - charcnt) * 100)/maxlimit) ;
	document.getElementById(counter).style.width =  parseInt((fieldWidth*percentage)/100)+"px";
	document.getElementById(counter).innerHTML="Limit: "+percentage+"%"
	// color correction on style from CCFFF -> CC0000
function setcolor(obj,percentage,prop){[prop] = "rgb(80%,"+(100-percentage)+"%,"+(100-percentage)+"%)";

CSS Needed Also.

The following css needs to be included also. This css is for the graphical display of the percentage or amount of text keyed:

<style type="text/css">
width: 1px;
height: 14px;
color: white;
font-size: 12px;
overflow: hidden;
background-color: navy;
padding-left: 5px;

HTML Code For Form Field

In this example, I am allowing a max of 2,000 characters:

MESSAGE: (2,000 character limit)
<textarea name="rtn_msg" rows="5" cols="40" message="Only 2000 Character allowed" wrap="virtual"
id="rtn_msg" onKeyDown="textCounter(this,'progressbar1',2000)"
onFocus="textCounter(this,'progressbar1',2000)" ></textarea>
<div id="progressbar1" class="progress"></div>


Submit a Comment

No comments yet.