user317005
user317005

Reputation:

Javascript / JQuery: How do I count the words separated with a comma?

Javascript:

$(document).ready(function()
{
    $('#field').keyup(function()
    {
        var count = '??';

        $('#count').html(count);
    });
});

HTML:

<input type="text" id="field" /> <span id="count">5</span>

Examples (words are always separated with a comma):

example 1: word, word word
count: (5 - 2) = 3

example 2: word
count: (5 - 1) = 4

example 3: word, word,
count: (5 - 2) = 3

example 4: word, word, word
count: (5 - 3) = 2

So, I need to count how many words there are separated with a comma, but for example as shown in example 3, it should not count them as 3 words only when there is a word also AFTER a comma.

And a user should not be allowed to enter more than 5 words.

Upvotes: 5

Views: 21853

Answers (3)

mattsven
mattsven

Reputation: 23293

Something like:

$("#input").keyup(function(){
    var value = $(this).val().replace(" ", "");
    var words = value.split(",");

    if(words.length > 5){
        alert("Hey! That's more than 5 words!");
        $(this).val("");
    }
});

jsFiddle example: http://jsfiddle.net/BzN5W/

EDIT:

Better example: http://jsfiddle.net/BzN5W/2/

$("#input").keypress(function(e){
    var value = $(this).val().replace(" ", "");
    var words = value.split(",");

    if(words.length > 5){
        //alert("Hey! That's more than 5 words!");
        e.preventDefault();
    }
});

Upvotes: 11

Simeon
Simeon

Reputation: 5579

I think you are looking for this:

$('#field').keyup(function(e){
    var count = $(this).val().split(',').length;
    $('#count').html(count);
    if(count > 4)
        e.preventDefault();
});

Upvotes: 0

Fareesh Vijayarangam
Fareesh Vijayarangam

Reputation: 5052

words.split(",").length should give you what you want, where words is a string containing the input.

Upvotes: 0

Related Questions