Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display word count while user is typing message and limit the word length to 300 words [closed]

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> 
like image 977
Psinyee Avatar asked Jun 15 '12 03:06

Psinyee


1 Answers

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/

like image 146
AvL Avatar answered Sep 21 '22 00:09

AvL