Javascript / JQuery: How do I count the words separated with a comma?
Javascript:
$(document).ready(function()
{
$('#f开发者_如何学编程ield').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.
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();
}
});
words.split(",").length
should give you what you want, where words
is a string containing the input.
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();
});
精彩评论