javascriptjqueryvalidationword-count

How to count words in JavaScript using JQuery


I have a simple html text box. When I "submit" the form that the text box is in, I would like to get a variable with the number of words inside using Jquery. I would also like to check if the inputted text is only letters, numbers and hyphens (also in jquery). I do not need to count the words as the user types, just when the form is submitted. The form won't submit if jquery is turned off so I guess there are no security risks by not using php. Is this true?

HTML:

<input type='text' name='name' id='name' />
<input type='button' value='Sign Up' id='signUp'>

JQUERY (attempt):

var wordcount = $('#name').val()  // i don't know how to count the words 

Solution

  • You would split the string and then count the length of the resulting array.

    $('input[type="submit"]').click( function() {
        var words = $('#name').val().split(' ');
        alert(words.length);
    });