Click here to Skip to main content
14,241,004 members
Rate this:
Please Sign up or sign in to vote.
Hello. I have a question regarding my codes. My question is "i want to put alert message if that person exceed words limitation". my code is function well and when exceed that person cannot type, however which part on javascript I want to put popup the alert message if he/she exceed?

What I have tried:

<textarea class="max" name="coverLetterText" id="coverLetterText" cols="80" rows="12" background placeholder="Make a Pitch not more than 400 words">

<pre><!-- script untuk textarea max-->  
<script>jQuery(document).ready(function($) {
    var max = 400;
    $('textarea.max').keypress(function(e) {
        if (e.which < 0x20) {
            // e.which < 0x20, then it's not a printable character
            // e.which === 0 - Not a character
            return;     // Do nothing
        }
        if (this.value.length == max) {
            e.preventDefault();
        } else if (this.value.length > max) {
            // Maximum exceeded
            this.value = this.value.substring(0, max);
        }
    });
}); //end if ready(fn)</script>
Posted
Updated 3-Aug-17 19:21pm

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

Right now, your this.value.length > 400 comparison checks the number of characters, and not words (such a check probably makes sense too -- but then the number would be bigger and that's not related to the number of word check). So you have to split up the string in words and compare the length of the array of words:
var words = this.value.split(/\W+/);
if (words.length > max) {
    e.preventDefault();
} else if (words.length > max) {
    alert("You can only have 400 words.");
    return; // 'exits' the current function
}

split splits a JavaScript string by a separator - this can be a string, or, like in this case, a regular expression[^]. Every time the regular expression gets matched, a split is performed. \W+ is the regular expression here: \W means 'non-word' character, + means '1 or more'. So this split call will split on all (series of) non-word characters. The + is necessary because otherwise you'd get empty strings in the word array if someone used multiple non-word characters next to each other.

This is the definition of \W:
Matches any character that is not a word character from the basic Latin alphabet. Equivalent to [^A-Za-z0-9_].

For example, /\W/ or /[^A-Za-z0-9_]/ matches "%" in "50%".
   
v2

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




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100