使用Javascript:
$(document).ready(function()
{
$('#field').keyup(function()
{
var count = '??';
$('#count').html(count);
});
});
HTML:
<input type="text" id="field" /> <span id="count">5</span>
示例(单词总是用逗号分隔):
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
所以,我需要计算用逗号分隔的单词数量,但是例如示例3 中所示,它不应该算作 3个单词只有在逗号后面还有一个单词时。
不应允许用户输入超过5个单词。
答案 0 :(得分:10)
类似的东西:
$("#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示例:http://jsfiddle.net/BzN5W/
修改强>
更好的例子: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();
}
});
答案 1 :(得分:0)
words.split(",").length
应该为您提供所需内容,其中words
是包含输入的字符串。
答案 2 :(得分:0)
我认为你正在寻找这个:
$('#field').keyup(function(e){
var count = $(this).val().split(',').length;
$('#count').html(count);
if(count > 4)
e.preventDefault();
});