PDA

View Full Version : Add a character count to a pre-existing html element.



Moru
Mar 31st, 2012, 04:11 AM
I am not a master of javascript. I am only beginning. I know how to edit most codes I come by to make them work for what I need them for, but I haven't really been able to get this concept to work. I know there is a way to count the characters of a text box. I have used them a thousand times. (Think twitter)

I am making a forum, and I am not self-hosting. So I don't have access to change all of the HTML on the forum software. So, here is what I want to do, and I really just need to know if its possible.

There is a reply box on this forum. A pre-existing element. It cannot be changed by going into the html, because I don't have access to it. I want a box to appear underneath it to count the number of characters that are typed into that box, and cut off if they go over.

I know of codes that allow you to count characters in a box you create, because you can add the "onkeyup=" to the html... I just don't have access to that part. Do you see where I'm getting at?

So to further illustrate, something like this:

http://i924.photobucket.com/albums/ad82/atomicsalsa/img.png

If it can be done, can someone show me how? I have the idea of how it might work, but I don't know enough to make my own code, only enough to figure out what existing code is talking about.

I am sorry if this doesn't make sense. I can try to explain further if need be.

Mishu
Mar 31st, 2012, 04:38 AM
<div>
<textarea id="txtInp" cols="20" rows="5"></textarea>
<div>No. of characters left:<span id="spCharsLeft"></span></div>
</div>

<script type="text/javascript">
var maxChars = 10;
function getCharsLeft(str){
str = (str.length < maxChars)? str : str.substring(0,maxChars);
txtInpObj.value = str;
spCharsLeftObj.innerHTML = (maxChars - str.length >= 0)? maxChars - str.length : 0 ;
}
txtInpObj = document.getElementById('txtInp');
txtInpObj.onkeyup=function(){
getCharsLeft(this.value);
}
spCharsLeftObj = document.getElementById('spCharsLeft');
spCharsLeftObj.innerHTML = maxChars;
</script>