Smart questions
Smart answers
Smart people
Join Tek-Tips Forums
INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Member Login




Remember Me
Forgot Password?
Join Us!

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips now!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

Join Tek-Tips
*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.
Jobs from Indeed

Link To This Forum!

Partner Button
Add Stickiness To Your Site By Linking To This Professionally Managed Technical Forum.
Just copy and paste the
code below into your site.

Word Count + Character LimitHelpful Member!(2) 

aarushi2001 (TechnicalUser) (OP)
19 Jan 06 12:23
Hi,

I have a javascript which works as follows:

when user exceeds number of words limit, it alerts the user. However, I would like to display a input box beneath my textarea, which displays number of words left. Also when user exceeds word limit, instead of a alert, I wont to stop user from continuing typing.. how can I do?
Helpful Member!  LFI (Programmer)
19 Jan 06 12:28
Words?  ...or characters?  Your posting title suggests both, but it seems like you're after words.

If it is words, I'm curious as to what the app is for and what the limit is.

Also, if you post what you've got already (that's counting words), it might be easier to make suggestions for what to add.

Dave


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
O Time, Strength, Cash, and Patience!  

aarushi2001 (TechnicalUser) (OP)
19 Jan 06 12:39
The title is cos I wanna combine two scripts.

I have a textarea with 100 words limit. All I want to do is when limit is up, it should not allow user to type.

The script I have is, it prompts/alerts user, which isnt helping me.
LFI (Programmer)
19 Jan 06 12:48
Your original post implied you have a script that counts the words.  Let's see it.


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
O Time, Strength, Cash, and Patience!  

Helpful Member!  theniteowl (Programmer)
19 Jan 06 12:53
It makes a big difference in your approach as to whether you mean words or characters.  Most times people have a character limit because the data goes into something (like a database) that has a maximum number of characters set.

In typing class back around 1980 they measured words-per-minute by stating every 5 characters equaled a word.
The sentence "Jack jumped over the candlestick." has a total number of words by calculated count of 6 3/5 though it has only 5 literal words.

If you are going by literal words then you have to consider how the words are delimited.  Will you count a space as the start of the next word?  If they double space it would throw off your count.  You could count whenever a space occurs followed by a character as the start of the next word and it would be more accurate but any character proceeded by a space counts as a whole word dramatically shortening the length of what they can type.

If you are going to count the total length of the string they enter then you need to decide if you are going to try to actively track what they have typed giving instant feedback or only after they leave that field.  I suspect you want it instantly which means you need to call a function to update the data every time a key is pressed or released.

Just thoughts.

Stamp out, eliminate and abolish redundancy!

LFI (Programmer)
19 Jan 06 13:09
Something like this might get you started...

(1) replace all instances of more than one space with just a single space.
(2) use spaces as a delimeter to split the textbox value into an array
(3) count the size of the array

CODE

var wordLimit = 500;
function countEm()
{
 var text1 = document.forms['myForm'].elements['myTextBox'].value;
 var text2 = text1.replace(/\s+/g, ' ');
 var text3 = text2.split(' ');
 var numberOfWords = text3.length;

 //write number of words left to another field
 document.forms['myForm'].elements['myTracker'].value = wordLimit - numberOfWords;

 if(numberOfWords > wordLimit)
  alert('too many!');
}

Dave


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
O Time, Strength, Cash, and Patience!  

BillyRayPreachersSon (Programmer)
19 Jan 06 14:49
A common drawback to scripts that disable input when a limit (word or character) is reached, is that the delete key can no longer be used to edit the text. Whatever your solution, you should try and avoid this pitfall.

Hope this helps,
Dan

Dan's Page @ Code Couch
http://www.codecouch.com/dan/


LFI (Programmer)
19 Jan 06 15:42
Ooh... I've got a little code that will prevent the user from going beyond the limit without disabling the box.  I was just having a little fun with it.  'hope it helps.

CODE

<html>
<head>
<script>
var wordLimit = 10;
var holdText;
var disabledBox = false;

function countEm()
{
 var text1 = document.forms['myForm'].elements['myTextBox'].value;
 var numberOfWords = doCount(text1);

 if(numberOfWords == wordLimit)
 {
  holdText = text1;
 }//end if

 document.forms['myForm'].elements['myTracker'].value = wordLimit - numberOfWords;

 if(numberOfWords >= wordLimit)
  disabledBox = true;
 else
  disabledBox = false;
}//end function

function doCount(textParam)
{
 //replace all instances of one-or-more spaces with a single space
 var text2 = textParam.replace(/\s+/g, ' ');

 //trim leading and tailing spaces
 while(text2.substring(0, 1) == ' ')
  text2 = text2.substring(1);
 while(text2.substring(text2.length-2, text2.length-1) == ' ')
  text2 = text2.substring(0,text2.length-1);

 var text3 = text2.split(' ');

 return text3.length;
}//end function

function maybeReset()
{
 if(disabledBox)
 {
  var currText = document.forms['myForm'].elements['myTextBox'].value;
  var newLength = doCount(currText);

  //prevent user from adding words, but not taking them away
  if(newLength > wordLimit)
  {
   document.forms['myForm'].elements['myTextBox'].value = holdText;
  }//end if
 }//end if
}//end function
</script>
</head>
<body>
<form name='myForm' >
<textarea name='myTextBox' onkeydown='countEm();' onkeyup='maybeReset();'></textarea><br />
<input type='text' name='myTracker' />
</form>
</body>
</html>

Dave


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
O Time, Strength, Cash, and Patience!  

glg1 (Programmer)
19 Jan 06 16:14
I ran across another means to count words in javascript...
http://home.cogeco.ca/~ve3ll/jstutorc.htm
Although I like Dave's better.

CODE

function CountWords(this_field, show_word_count, show_char_count) {
if (show_word_count===undefined) {show_word_count=true;} //show is default
if (show_char_count===undefined) {show_char_count=false;} //noshow is deft
el=document.getElementById(this_field);
char_count=el.value.length;          // very crude measure
fullStr=el.value+" ";   // add space delimiter to end of text
initial_whitespace_rExp= /^[^A-Za-z0-9]+/gi; //use for complex whitespace
left_trimmedStr=fullStr.replace(initial_whitespace_rExp, " ");
non_alphanumerics_rExp=/[^A-Za-z0-9]+/gi;    // and for delimiters
cleanedStr=left_trimmedStr.replace(non_alphanumerics_rExp, " ");
splitString=cleanedStr.split(" ");word_count=splitString.length -1;
if (fullStr.length <2) {word_count=0;}
if (word_count==1){wordOrWords=" word";}else{wordOrWords=" words";}
if (char_count==1){charOrChars=" character";}else{charOrChars=" characters";}
if (show_word_count && show_char_count) {
   msg="Word Count:\n"+" "+word_count+wordOrWords+"\n";
   msg += " "+char_count+charOrChars;window.alert(msg);
   } else {
   if (show_word_count) {alert("Word Count:  "+word_count+wordOrWords);}
   else {
      if (show_char_count) {
         window.alert("Character Count:  "+char_count+charOrChars);}
      }
   }
return word_count;}
aarushi2001 (TechnicalUser) (OP)
20 Jan 06 8:20
Thanks everybody, u guys r brilliant :D.. thank u so much!!
LFI (Programmer)
20 Jan 06 8:51
Be forewarned, aarushi2001... If a user types somewhere else and then copies/pastes into the textarea in my example, things fall apart a little bit.  Not too badly, but some.

Also, you might consider changing the line:

CODE

if(numberOfWords == wordLimit)
 {
  holdText = text1;
 }//end if

to:

CODE

if(numberOfWords <= wordLimit)
 {
  holdText = text1;
 }//end if

...particularly if you're worried about the cutting/pasting thing.  It might just be unnecessary processing if you're not.

Dave


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
O Time, Strength, Cash, and Patience!  

tmcneil (TechnicalUser)
25 Apr 06 13:03
I was wondering if I could get some help on this.  I too have a character counter, not a word counter.  I have a textarea control where I call the character counter on keystroke. html code:

CODE

<td colspan="1" align="left" valign="top">
            <textarea cols="88" rows="14" id="message" name="message" title="Message Text" STYLE="width: 99%;" OnKeyPress="changeText();"
             onKeyUp="charCount('message','charBann','{CHAR} characters left.');"><%=message%></textarea>
            <br>
            <span class="dlgspan" id="charBann" name="charBann" class="minitext">512 characters left.</span>
            <br>      
        </td>
javascript code:

CODE

function charCount(message,charBann,text)
{
    var messageObj = document.getElementById("message");
    var charBannObj = document.getElementById("charBann");
    var longitude=512 - messageObj.value.length;

    if(longitude <= 0)
    {
        longitude=0;
        text='<span class="disable"> '+text+' </span>';
        messageObj.value=messageObj.value.substr(0,512);
    }
    charBannObj.innerHTML = text.replace("{CHAR}",longitude);
}// end charCount function
It works very well by the way, except when the page refreshes.  The textarea box loses focus and the character count goes back to 512.  it will update again when you put the cursor in the textarea and strike a key.  So, is there a better way to count the characters so that the count is always correct even if there is a page refresh?

Thanks,
Todd
theniteowl (Programmer)
25 Apr 06 13:14
The problem is that you set a default value of 512 prior to any event being able to happen on the text box.  
What you could do is use the onload event to execute the function to update the count so as soon as the page loads it sets the correct value without the field having to receive focus and a keypress first.

Paranoid?  ME??    Who wants to know????

tmcneil (TechnicalUser)
25 Apr 06 13:45
theniteowl,

Should I change the default to be something else...

So, I would replace this event

CODE

onKeyUp="charCount('message','charBann','{CHAR} characters left.');"

with...

I guess I don't quite understand what the syntax would be.

Todd
theniteowl (Programmer)
25 Apr 06 13:59
What happens is this:
You execute your ASP code which sets the value for what is going into the input field.
Your page get's displayed with the value passed into the input field via your ASP variable message.  But the text below it that says "512 characters left." is hard coded into your HTML and so of course does not accurately reflect how many characters are available.

When someone clicks on the input field and hits a key your function executes, counts the characters in the input field and then sets the new number of characters message.

Instead of waiting for someone to click on the input and press a key just modify your <body> tag like this:
<<body onload="charCount('message','charBann','{CHAR} characters left.');">

Then, as soon as the page finishes loading the charCount function runs, counts the actual characters and sets the message without waiting for the client to do anything.

Another approach would be on your ASP code side.  Just grab the length of the value stored in the message variable and store it in a variable like msgLength.
Then alter your message section to something like this:
<span class="dlgspan" id="charBann" name="charBann" class="minitext"><%=msgLength%> characters left.</span>
Using this method the correct value is set in the message as the page is displayed.

Paranoid?  ME??    Who wants to know????

tmcneil (TechnicalUser)
25 Apr 06 14:29
Brilliant!  I used the body onload event and it worked like a charm. Thanks, niteowl.

Todd

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members!

Back To Forum

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close