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.

Javascript

<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
	setcolor(document.getElementById(counter),percentage,"background-color");
	}
}
function setcolor(obj,percentage,prop){
	obj.style[prop] = "rgb(80%,"+(100-percentage)+"%,"+(100-percentage)+"%)";
}
</script>

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">
.progress{
width: 1px;
height: 14px;
color: white;
font-size: 12px;
overflow: hidden;
background-color: navy;
padding-left: 5px;
}
</style>

HTML Code For Form Field

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

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

Comments

Submit a Comment

No comments yet.