5

How do I limit the short messages to 300 words and display the word count on top of the message box? The number on top of the message box doesn't seem to be decreasing when I try to type in something.

Javascript:

<script type="text/javascript" language="javascript"> 
var content;
$('textarea').on('keyup', function(){
    var words = $(this).val().split(" ").length;
    $('#myWordCount').text("("+(300-words)+" words left)");
    if(words>=300){
        $(this).val(content);
        alert('no more than 300 words, please!');
    } else {    
        content = $(this).val();
    }
});
</script>

Message Form:

    <form action="read_message.php" method="post"> 
 <table class="form_table"> 
  <tr> 
    <td style="font-weight:bold;">Subject:</td> 
    <td><input style=" width:300px" name="form_subject"/></td> 
    <td></td> 
  </tr> 
  <tr> 
    <td style="font-weight:bold;">Message:</td> 
    <td id="myWordCount">300 words left</td> 
    <td></td> 
  </tr> 
  <tr> 
    <td><input type="hidden" name="sender_id" value="<?php echo $sender_id?>"></td> 
    <td><textarea cols="50" rows="4" name="form_message"></textarea></td> 
    <td valign="bottom"><input type="submit" name="submit_message" value="send"></td> 
  </tr> 
 </table> 
</form> 
Psinyee
  • 185
  • 1
  • 4
  • 14
  • 3
    IMHO you should rather limit letters than words – AvL Jun 15 '12 at 03:59
  • 1
    'How to achieve' sounds very vague. Tell us what part you expect help with us, otherwise we cannot write it all for you. – Anonymous Jun 15 '12 at 04:03
  • Eww... tables... http://stackoverflow.com/questions/83073/why-not-use-tables-for-layout-in-html – ubiquibacon Jun 15 '12 at 04:04
  • `return false`doesn't work. See my edited post. And you should wrap your jQuery function with `$(document).ready(function(){ ... )` – AvL Jun 15 '12 at 04:53

5 Answers5

6

To limit the number of letters used try something like this:

var content;
$('textarea').on('keyup', function(){
    var letters = $(this).val().length;
    $('#myLetterCount').text(301-letters+" letters left");
    // limit message
    if(letters>=301){
        $(this).val(content);
        alert('no more than 300 letters, please!');
    } else {    
        content = $(this).val();
    }
});

to count the words use the following:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    var content;
    $('textarea').on('keyup', function(){
        // count words by whitespace
        var words = $(this).val().split(/\s+/).length;
        $('#myWordCount').text(301-words+" words left");
        // limit message
        if(words>=301){
            $(this).val(content);
            alert('no more than 300 words, please!');
        } else {    
            content = $(this).val();
        }
    });
});
</script>

demo: http://jsfiddle.net/NVSN7/6/

AvL
  • 3,083
  • 1
  • 28
  • 39
  • He asked for a word count, not a character count. – Justin Morgan - On strike Jun 15 '12 at 04:07
  • @JustinMorgan: true, edited post. But word count makes little sense. What if somebody only uses very long words? – AvL Jun 15 '12 at 04:15
  • Maybe if the limiting factor isn't the size of his database, but the patience of the message's recipient. It would seem to make sense then. – Justin Morgan - On strike Jun 15 '12 at 04:19
  • @AvL Sorry... I had just tried out the code provided by you, but the display doesn't seem to work for me. I already edited my codes accordingly, and I can't find what is the mistake. – Psinyee Jun 15 '12 at 04:36
  • @Psinyee `return false` doesn't work. Did you try my EDITED jsfiddle? Works for me in all major browsers mac & PC: http://jsfiddle.net/NVSN7/2/ – AvL Jun 15 '12 at 04:48
  • @AvL yes, I did try out the editied jsfiddle and I already edited the post accordingly. But I'm not sure why the number is not decreasing when I type in my message. – Psinyee Jun 15 '12 at 05:45
  • Does my jsfiddle not work for you or is it only your own page not working? Did you include jQuery 1.7? See my edited post second code section. Good luck! – AvL Jun 15 '12 at 06:26
  • 1
    Note that this won't split on tabs, carriage returns, or weird whitespace characters like U+00A0. It also will split multiple times on 2 or more spaces in a row. I suggest splitting on `/\s+/` instead. – Justin Morgan - On strike Jun 15 '12 at 15:19
  • @JustinMorgan You are right, your regex covers the full range of word separators. Updated answer. Thanks – AvL Jun 17 '12 at 10:52
1

so, this uses a regex to get word boundaries. alter the regex to change what it considers a 'word'. on keypress, the word count is updated as applicable and sets the text.

$(function(){
  var wordcount = /\b/g;

  $('form').on({'keypress':function(event){
    var wordArray = $(this).val().match(wordcount);
   $("#wordcount").text(wordArray?event.data.max - wordArray.length /2:event.data.max);
  }},'textarea',{max:300});
});
DefyGravity
  • 5,681
  • 5
  • 32
  • 47
1

I agree with some commenters that limiting characters may be more useful to do. However, you can definitely count words, depending on how you define a "word":

function countWords(str) {
    return str.split(/\s+/).length;
}

$('textarea[name="form_message"]').on('keyup', function () {
    var words = countWords($(this).val());
    $('#myWordCount').text(300 - words + ' words left');
}

If you want to count letters instead, you can just take out .split(/\s+/) above and it should work.

Justin Morgan - On strike
  • 30,035
  • 12
  • 80
  • 104
0

Try this... http://www.jamesfairhurst.co.uk/posts/view/jquery_word_character_counter

shahbaz
  • 372
  • 1
  • 3
  • 18
-1

try this one: i use js here.

function countWord()
{
    var str = document.getElementById("myTextarea").value;
    var subStr = str.split(" ");

    if(subStr.length == 301)
    {
        document.getElementById("myTextarea").value = str.slice(0, -1);
        alert("Limit Reached!");
        return false;
    }
}

<textarea id="myTextarea" onkeypress="return countWord();" style="width:300px; height:200px;"></textarea>
sephoy08
  • 1,104
  • 7
  • 16
  • This will fail if the user uses cut & paste to enter more than one word at a time. If the user is at 299 words, then pastes in 5 words at once, `subStr.length == 301` will never be true, and he can continue happily adding all the words he wants. – Justin Morgan - On strike Jun 15 '12 at 15:31