Click here to Skip to main content
15,749,352 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
please help, I am having an issue with the textarea count, it does stop the typing once the number of characters is reached but its not showing the count down.

the code I am using

XML
<textarea id="notes" name="fixlength" maxlength="300" lengthcut="true" rows="5" cols="45"><?php if(isset($rec2['notes']) && $rec2['notes']!='') echo stripslashes($rec2['notes']); ?></textarea>
</p>
<label></label>

<script type="text/javascript" language="javascript" src="/js/charcount.js"></script>



Javascirpt:

/*
If you want to use this script, please keep the original author in this header!

Purpose:	Script for applying maxlengths to textareas and monitoring their character lengths.
Author: 	James O'Cull
Date: 		08/14/08

To use, simply apply a maxlenth value to a textarea.
If you need it to prevent typing past a certain point, add lengthcut="true"

Example:
<textarea maxlength="1000" lengthcut="true"></textarea>

If you add a new text area with javascript, simply call parseCharCounts() again find the new textarea(s) and label them!
*/
var LabelCounter = 0;

function parseCharCounts()
{
	//Get Everything...
	var elements = document.getElementsByTagName('textarea');
	var element = null;
	var maxlength = 9;
	var newlabel = null;
	
	for(var i=0; i < elements.length; i++)
	{
		element = elements[i];
		
		if(element.getAttribute('maxlength') != null && element.getAttribute('limiterid') == null)
		{
			maxlength = element.getAttribute('maxlength');
			
			//Create new label
			newlabel = document.createElement('label');
			newlabel.id = 'limitlbl_' + LabelCounter;
			newlabel.style.color = 'red';
			newlabel.style.display = 'block'; //Make it block so it sits nicely.
			newlabel.innerHTML = "Updating...";
			
			//Attach limiter to our textarea
			element.setAttribute('limiterid', newlabel.id);
			element.onkeyup = function(){ displayCharCounts(this); };
			
			//Append element
			element.parentNode.insertBefore(newlabel, element);
			
			//Force the update now!
			displayCharCounts(element);
		}
		
		//Push up the number
		LabelCounter++;
	}
}

function displayCharCounts(element)
{
	var limitLabel = document.getElementById(element.getAttribute('limiterid'));
	var maxlength = element.getAttribute('maxlength');
	var enforceLength = false;
	if(element.getAttribute('lengthcut') != null && element.getAttribute('lengthcut').toLowerCase() == 'true')
	{
		enforceLength = true;
	}
	
	//Replace \r\n with \n then replace \n with \r\n
	//Can't replace \n with \r\n directly because \r\n will be come \r\r\n

	//We do this because different browsers and servers handle new lines differently.
	//Internet Explorer and Opera say a new line is \r\n
	//Firefox and Safari say a new line is just a \n
	//ASP.NET seems to convert any plain \n characters to \r\n, which leads to counting issues
	var value = element.value.replace(/\u000d\u000a/g,'\u000a').replace(/\u000a/g,'\u000d\u000a');
	var currentLength = value.length;
	var remaining = 0;
	
	if(maxlength == null || limitLabel == null)
	{
		return false;
	}
	remaining = maxlength - currentLength;
	
	if(remaining >= 0)
	{
		limitLabel.style.color = 'black';
		limitLabel.innerHTML = remaining + ' character';
		if(remaining != 1)
			limitLabel.innerHTML += 's';
		limitLabel.innerHTML += ' remaining';
	}
	else
	{
		if (enforceLength == true) {
			value = value.substring(0, maxlength);
			element.value = value;
			element.setSelectionRange(maxlength, maxlength);
			limitLabel.style.color = 'green';
			limitLabel.innerHTML = '0 characters remaining';
		}
		else {
			//Non-negative
			remaining = Math.abs(remaining);
			
			limitLabel.style.color = 'red';
			limitLabel.innerHTML = 'Over by ' + remaining + ' character';
			if (remaining != 1) 
				limitLabel.innerHTML += 's';
			limitLabel.innerHTML += '!';
		}
	}
}

//Go find our textareas with maxlengths and handle them when we load!
parseCharCounts();
Posted
Comments
Maciej Los 23-May-13 17:28pm    
I'm not expert in this, but your textarea "name" is: textarea id="notes", but inside the function you're trying to find control by its name in this way: document.getElementsByTagName('textarea'). try to change to document.getElementsByTagName('notes').
AbdelUK 23-May-13 17:36pm    
I have changed the name to notes and still no joy :(
Mohibur Rashid 23-May-13 20:38pm    
valid function to access a element with object would be
document.getElementById("notes")
also
document.queryselector("#notes") will work too. but not all browser support this.
enhzflep 23-May-13 18:08pm    
What do you mean by "but its not showing the count down"?

When I try the code, it allows me to type until there are 0 characters left. At this point, the 'remaining char count' changes from black to green.
If I try to paste too much text in, the count is red and tells me that it's XX chars too long.

(Also, the id='notes' is not incompatible with getElementsByTagName('textarea') - i.e, you've given the field a name, suitable for form submissions. The code then looks for all textarea elements on the page and applies the JS to each of them)
AbdelUK 23-May-13 18:37pm    
Thank u for the reply. It does work for me too when I test it on a new page/ site. But if I try
To add it to my main Php page with the code below it doesn't show the count down. I hope I made sense.
thank you in advance

1 solution

thats the full code of my page:

XML
<? session_start();
require "include/connect.php";
require "include/settings.php";
extract($_REQUEST);
//extract the request arrray for future use, this will allow variable names that have been passed
//from another form to be used without the need to reference the request array.

//$offenses1=substr( $offenses,1,strlen( $offenses));

//echo $offendersurname;
//echo $vrecid;

if($type == 'first')
{
//$st1date=explode("/",$_REQUEST['sentensedate']);
//$st2sate=$st1date[2]."-".$st1date[1]."-".$st1date[0];



$stmt= mssql_init("sp_InsertOffenderAndUpdateCaseNewAuto");
    //set params for Store Proc for offender passed information from 2nd page when user pressed back arrow
    mssql_bind($stmt, '@offenderForename', $offenderforename, SQLVARCHAR,false,false,255);
    mssql_bind($stmt, '@offenderSurname', $offendersurname, SQLVARCHAR,false,false,255);
    mssql_bind($stmt, '@offenderCRN', $offendercrn, SQLVARCHAR,false,false,50);
    mssql_bind($stmt, '@offenderDOB', $offenderdob, SQLVARCHAR,false,false,10);
    //mssql_bind($stmt, '@offenderOffenses', $offenses, SQLVARCHAR,false,false,255);
    mssql_bind($stmt, '@offenderPrisonNumber', $prisonnumber1, SQLVARCHAR,false,false,255);
    mssql_bind($stmt, '@offenderPrisonLocation', $prisonlocation, SQLVARCHAR,false,false,255);
    mssql_bind($stmt, '@offenderTelNo', $telephoneno, SQLVARCHAR,false,false,30);
     //set params for Store Proc for updated case info passed information from 2nd page when user pressed back arrow

    mssql_bind($stmt, '@sentensedate', $sentensedate, SQLVARCHAR,false,false,255);
    mssql_bind($stmt, '@court', $court, SQLVARCHAR,false,false,255);
    mssql_bind($stmt, '@sentense', $sentense, SQLVARCHAR,false,false,255);
    mssql_bind($stmt, '@remand', $remand, SQLVARCHAR,false,false,255);
    mssql_bind($stmt, '@offendermanager', $offendermanager, SQLVARCHAR,false,false,255);
    mssql_bind($stmt, '@location', $location, SQLVARCHAR,false,false,255);
    mssql_bind($stmt, '@dateofsentense', $dateofsentense, SQLVARCHAR,false,false,255);
    mssql_bind($stmt, '@hdc', $hdc, SQLVARCHAR,false,false,10);
    mssql_bind($stmt, '@ard', $ard, SQLVARCHAR,false,false,10);
    mssql_bind($stmt, '@led', $led, SQLVARCHAR,false,false,10);
    mssql_bind($stmt, '@sed', $sed, SQLVARCHAR,false,false,10);
    mssql_bind($stmt, '@hospitalorder', $hospitalorder, SQLVARCHAR,false,false,255);
    mssql_bind($stmt, '@referral', $referral, SQLVARCHAR,false,false,255);
    mssql_bind($stmt, '@id', $vrecid, SQLINT4,false,false,10);
    mssql_bind($stmt, '@offenderid', $offenderid, SQLINT4,true,false,10);

    $tmp=mssql_execute($stmt);
    //echo $offenderid;
    if (!$tmp)
    {
    echo "<table><tr><td ><img src='images/sqlerror.png' width='64' height='64' /></td><td align='center'><blink>" . mssql_get_last_message() . "<br /><strong>PLEASE REPORT THE ABOVE ISSUE TO YOUR ADMIN TEAM</strong></blink></td><td><img src='images/sqlerror.png' width='64' height='64' /></tr></table>";
    exit();
    }
    //*******************
    //New offence code below
    if (isset($_REQUEST['offenses']) )
                        {
                        $v = unserialize(urldecode(stripslashes(($offenses[0]))));
                        $q=0;
                        foreach ($v as $a)
                        {
                        if($q==0)
                        {
                        if($originalfirstoffence != $a)
                        {
                            $stmt= mssql_init("sp_remOffCase");
                            mssql_bind($stmt, '@id', $originalfirstoffenceid, SQLINT4,false,false,10);
                            mssql_execute($stmt);

                        }
                        }
                            if (!is_null($a))
    {

                        $stmt= mssql_init("sp_InsertOffenceCase");
                        mssql_bind($stmt, '@offence', $a, SQLVARCHAR,false,false,30);
                        mssql_bind($stmt, '@offenderid',$offenderid,SQLINT4,false,false,10);
                        mssql_bind($stmt, '@caseid',$vrecid,SQLVARCHAR,false,false,50);
                                        $tmp9=mssql_execute($stmt);
                                        $q++;
                                        if (!$tmp9)
    {
    echo "<table><tr><td ><img src='images/sqlerror.png' width='64' height='64' /></td><td align='center'><blink>" . mssql_get_last_message() . "<br /><strong>PLEASE REPORT THE ABOVE ISSUE TO YOUR ADMIN TEAM</strong></blink></td><td><img src='images/sqlerror.png' width='64' height='64' /></tr></table>";
    exit();
    }
    }

                                        }

                                        }
    //End of new offence code
    //*******************
}
//$sel2="select * from ".VICTIM." where id='$vrecid'";
//$res2=mssql_query($sel2);
//$rec2=mssql_fetch_array($res2);
$stmt=mssql_init("sp_GetLastPageVictim");
mssql_bind($stmt,'@id',$vrecid,SQLINT4,false,false,10);
$res2=mssql_execute($stmt);
if (!$res2)
    {
    echo "<table><tr><td ><img src='images/sqlerror.png' width='64' height='64' /></td><td align='center'><blink>" . mssql_get_last_message() . "<br /><strong>PLEASE REPORT THE ABOVE ISSUE TO YOUR ADMIN TEAM</strong></blink></td><td><img src='images/sqlerror.png' width='64' height='64' /></tr></table>";
    exit();
    }
$rec2=mssql_fetch_array($res2);
//echo mssql_get_last_message();
//echo $rec2['contactvcr'];
//echo $rec2['contactvcr'];
//echo $rec2['status'];
$selectliasion="select * from ".STAFF." where id='$rec2[addedby]'";
$resultliasion=mssql_query($selectliasion);
$recordliasion=mssql_fetch_array($resultliasion);
?>
<div style="display:none"><input type="text" id="pageno" name="pageno" value="3" /></div>
<input type="hidden" id="vrecid" name="vrecid" value="<?=$vrecid;?>" />
<input type="hidden" id="vicid" name="vicid" value="<?=$vicid;?>" />
<table width="100%" cellspacing="0" cellpadding="0">
<tr>
<td bgcolor="#ffffff"  align="center" valign="top">
<table width="750" border="0" cellspacing="0" cellpadding="0">
<tr>
<td valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td valign="top">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td colspan="3" valign="top"><? require 'menu.php'; ?></td>
</tr>
<tr>
<td colspan="3"><table width="100%" cellpadding="0" cellspacing="0"><tr>
<td width="1" background="images/line4.jpg"  ><img src="images/line4.jpg" width="1" height="25" /></td>
<td width="121" height="30" background="images/000.jpg" class="style7"  style="padding-left:10px;">&nbsp;</td>
<td width="1" background="images/line4.jpg"  ><img src="images/line4.jpg" width="1" height="25" /></td>
<td width="157" background="images/001.jpg" class="style7"  style="padding-left:10px;">&nbsp;</td>
<td width="1" background="images/line4.jpg"  ><img src="images/line4.jpg" width="1" height="25" /></td>
<td width="63" background="images/000.jpg" class="style7" style="padding-left:10px;" >&nbsp;</td>
<td width="1" background="images/line4.jpg"  ><img src="images/line4.jpg" width="1" height="25" /></td>
<td width="103" background="images/001.jpg" class="style7"  style="padding-left:10px;"></td>
<td width="1" background="images/line4.jpg"  ><img src="images/line4.jpg" width="1" height="25" /></td>
<td width="108" background="images/000.jpg" class="style7"   style="padding-left:10px;">&nbsp;</td> <td width="1" background="images/line4.jpg"  ><img src="images/line4.jpg" width="1" height="25" /></td>
<td width="136" background="images/001.jpg" class="style7"   style="padding-left:10px;">&nbsp;</td>
<td width="1" background="images/line4.jpg"  ><img src="images/line4.jpg" width="1" height="25" /></td>
</tr></table></td>
</tr>
<tr>
<td colspan="3"><table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="1" background="images/loginline1.jpg"></td>
<td height="180" valign="top" bgcolor="#fafafa">
<input name="rand_record_id" id="rand_record_id" type="hidden" value="<?php echo $rec2['recordid'];?>" />
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="4">&nbsp;</td>
<td width="10" class="style5">&nbsp;</td>
<td width="730" class="style5">&nbsp;</td>
<td width="4">&nbsp;</td>
</tr>
<tr>
  <td>&nbsp;</td>
  <td>&nbsp;</td>
  <td><table width="100%" border="0" cellspacing="0" cellpadding="3">
    <tr>
      <td height="30" colspan="4" align="left" class="style3" style="color:#000000">OTHER INFORMATION </td>
      </tr>
    <tr>
      <td width="138" height="30" align="left" class="style31" >Case Notes</td>
      <td width="214"  align="left"><br>

 <textarea id="notes" name="fixlength" maxlength="300" lengthcut="true" rows="5" cols="45"><?php if(isset($rec2['notes']) && $rec2['notes']!='') echo stripslashes($rec2['notes']); ?></textarea>
</p>
<label></label>

<script type="text/javascript" language="javascript" src="/js/charcount.js"></script>

         </td>
      <td width="175" height="30" align="left" class="style31" >Status</td>
      <td width="179" align="left"><select id="status" name="status" style="width:150px;" title="Status">
        <option value="">Select</option>
        <option value="Active" <? if($rec2['status']=='Active') {?> selected="selected" <? } ?>>Active </option>
        <option value="Closed" <? if($rec2['status']=='Closed') {?> selected="selected" <? } ?>>Closed </option>
        <option value="Discretionary" <? if($rec2['status']=='Discretionary') {?> selected="selected" <? } ?>>Discretionary </option>
        <option value="Gutted" <? if($rec2['status']=='Gutted') {?> selected="selected" <? } ?>>Gutted </option>
        <option value="Inactive" <? if($rec2['status']=='Inactive') {?> selected="selected" <? } ?>>Inactive </option>
        <option value="Open" <? if($rec2['status']=='Open') {?> selected="selected" <? } ?>>Open</option>
        <option value="Pending" <? if($rec2['status']=='Pending') {?> selected="selected" <? } ?>>Pending </option>
        </select></td>

      </tr>
    </table></td>
  <td>&nbsp;</td>
</tr>
<tr>
  <td>&nbsp;</td>
  <td align="right"></td>
  <td align="right"><table width="65%" border="0" cellspacing="0" cellpadding="0">
  <tr>
  <td width="302" class="style31" align="center">Save the case to return to a blank front sheet </td>
  <td width="94"><input name="submit4" type="submit"  value="Save" title="Save" onClick="workisdone=true;"   style="background:url(images/button.png); border:none; height:35px; width:198px; font-size:14px; font-weight:bold"  /></td>
  <td width="11">&nbsp;</td>
  </tr>
  </table></td>
  <td>&nbsp;</td>
</tr>
<tr><td colspan="4" style="font-size:9px;">&nbsp;</td></tr>
</table>                                </td>
<td width="1"  background="images/loginline1.jpg" align="right"></td>
</tr>
<tr>
<td colspan="3" background="images/loginline2.jpg"><img src="images/loginline2.jpg" width="4" height="1" /></td>
</tr>
</table></td>
</tr>
</table></td>
</tr>
</table></td>
</tr>
</table>
</td>
</tr>
<tr>
<td  height="74" background="images/footerbg.jpg" align="left">&nbsp;
<input type="button" id="submit" name="submit" style="background:url(images/leftarrow.png); border:none; width:32px; height:32px; cursor:pointer;" title="Previous" value="" onclick=' validate5()' /></td>
</tr>
</table>
<script type="text/javascript">
function addmoreprisonname()
{
var frm_obj = window.document.victim;
var tbody = document.getElementById("table1").getElementsByTagName("tbody")[2];
var nUploads = parseInt(frm_obj.noofrows.value);
var row1 = document.createElement("TR");
var cell3 = document.createElement("TD");
cell3.setAttribute("align","center");
var cell2 = document.createElement("TD");
cell2.setAttribute("align","left");
var eInput1 = document.createElement("input");
eInput1.setAttribute("type","text");
eInput1.setAttribute("name","prisonname[]");
eInput1.setAttribute("id","prisonname_"+nUploads);
cell2.appendChild(eInput1);
var img = document.createElement("img");
img.setAttribute("src","images/delete.png");
img.setAttribute("style","cursor:hand; !important; cursor:pointer; !important; position: relative;padding-left:2px;");
img.setAttribute("alt","Remove this Image");
img.setAttribute("title","Remove this Image");
img.onclick = function() { removetr(row1,nUploads); }
cell2.appendChild(img);
row1.appendChild(cell3);
row1.appendChild(cell2);
tbody.appendChild(row1);
frm_obj.noofrows.value = nUploads+1;
}
function removetr(row1)
{
row1.parentNode.removeChild(row1);
document.getElementById("noofrows").value = document.getElementById("noofrows").value - 1;
document.getElementByid('removedrows').value=document.getElementByid('removedrows').value+",";
}
function addmorevictimtelephone()
{
var frm_obj = window.document.victim;
var tbody = document.getElementById("table1").getElementsByTagName("tbody")[1];
var nUploads = parseInt(frm_obj.noofrows1.value);
var row1 = document.createElement("TR");
var cell3 = document.createElement("TD");
cell3.setAttribute("align","center");
cell3.setAttribute("colspan","3");
var cell2 = document.createElement("TD");
cell2.setAttribute("align","left");
var eInput1 = document.createElement("input");
eInput1.setAttribute("type","text");
eInput1.setAttribute("name","victimtelephone[]");
eInput1.setAttribute("id","victimtelephone_"+nUploads);
cell2.appendChild(eInput1);
var img = document.createElement("img");
img.setAttribute("src","images/delete.png");
img.setAttribute("style","cursor:hand; !important; cursor:pointer; !important; position: relative;padding-left:2px;");
img.setAttribute("alt","Remove this Image");
img.setAttribute("title","Remove this Image");
img.onclick = function() { removetrvictimtelephone(row1,nUploads); }
cell2.appendChild(img);
row1.appendChild(cell3);
row1.appendChild(cell2);
tbody.appendChild(row1);
frm_obj.noofrows.value = nUploads+1;
}
function removetrvictimtelephone(row1)
{
row1.parentNode.removeChild(row1);
document.getElementById("noofrows1").value = document.getElementById("noofrows1").value - 1;
document.getElementByid('removedrows1').value=document.getElementByid('removedrows1').value+",";
}
function addmoreoffenses()
{
var frm_obj = window.document.victim;
var tbody = document.getElementById("table2").getElementsByTagName("tbody")[1];
var nUploads = parseInt(frm_obj.noofrows2.value);
var row1 = document.createElement("TR");
var cell3 = document.createElement("TD");
cell3.setAttribute("align","center");
cell3.setAttribute("colspan","1");
var cell2 = document.createElement("TD");
cell2.setAttribute("align","left");
var eInput1 = document.createElement("input");
eInput1.setAttribute("type","text");
eInput1.setAttribute("name","offenses[]");
eInput1.setAttribute("id","offenses_"+nUploads);
cell2.appendChild(eInput1);
var img = document.createElement("img");
img.setAttribute("src","images/delete.png");
img.setAttribute("style","cursor:hand; !important; cursor:pointer; !important; position: relative;padding-left:2px;");
img.setAttribute("alt","Remove this Image");
img.setAttribute("title","Remove this Image");
img.onclick = function() { removetrvictimtelephone(row1,nUploads); }
cell2.appendChild(img);
row1.appendChild(cell3);
row1.appendChild(cell2);
tbody.appendChild(row1);
frm_obj.noofrows.value = nUploads+1;
}
function removetroffenses(row1)
{
row1.parentNode.removeChild(row1);
document.getElementById("noofrows2").value = document.getElementById("noofrows2").value - 1;
document.getElementByid('removedrows2').value=document.getElementByid('removedrows2').value+",";
}
function addmorelinkedto()
{
var frm_obj = window.document.victim;
var tbody = document.getElementById("table3").getElementsByTagName("tbody")[1];
var nUploads = parseInt(frm_obj.noofrows3.value);
var row1 = document.createElement("TR");
var cell5 = document.createElement("TD");
cell5.setAttribute("align","center");
cell5.setAttribute("colspan","1");
var cell3 = document.createElement("TD");
cell3.setAttribute("align","center");
cell3.setAttribute("colspan","1");
var cell2 = document.createElement("TD");
cell2.setAttribute("align","left");
var eInput1 = document.createElement("input");
eInput1.setAttribute("type","text");
eInput1.setAttribute("name","linkedto[]");
eInput1.setAttribute("id","linkedto_"+nUploads);
cell2.appendChild(eInput1);
var img = document.createElement("img");
img.setAttribute("src","images/delete.png");
img.setAttribute("style","cursor:hand; !important; cursor:pointer; !important; position: relative;padding-left:2px;");
img.setAttribute("alt","Remove this Image");
img.setAttribute("title","Remove this Image");
img.onclick = function() { removetrvictimtelephone(row1,nUploads); }
cell2.appendChild(img);
var cell4= document.createElement("TD");
cell4.setAttribute("align","left");
var eInput2 = document.createElement("input");
eInput2.setAttribute("type","text");
eInput2.setAttribute("name","caseno[]");
eInput2.setAttribute("id","caseno_"+nUploads);
cell4.appendChild(eInput2);
row1.appendChild(cell5);
row1.appendChild(cell2);
row1.appendChild(cell3);
row1.appendChild(cell4);
tbody.appendChild(row1);
frm_obj.noofrows.value = nUploads+1;
}
function removetrlinkedto(row1)
{
row1.parentNode.removeChild(row1);
document.getElementById("noofrows3").value = document.getElementById("noofrows3").value - 1;
document.getElementByid('removedrows3').value=document.getElementByid('removedrows3').value+",";
}


</script>
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900