如何限制文本框中包含少于3个逗号?

时间:2011-11-14 17:05:59

标签: javascript jquery

例如,我们有一个文本框,用于博客的标签。我想要的是我想限制标签的数量是有限的。 例如,“虚拟主机,php,windows8”。 当用户尝试在另一个文本框中输入以逗号开头的文本框时,文本框将不允许他编写它。

3 个答案:

答案 0 :(得分:4)

keypress处理程序中,捕获event对象并执行;

if (event.which == 44 && $(this).val().split(",").length > 2) {
    event.preventDefault();
}

在这里看到它; http://jsfiddle.net/5L7mU/

答案 1 :(得分:2)

我们可以将这个问题分成3个较小的问题。

首先,我们需要一种方法来阻止用户将内容写入文本框。当您在keypress上挂钩回调时,传递的事件有一个名为preventDefault的方法可以完成这项工作。所以阻止所有输入:

$("input").keypress(function(event) {
    event.preventDefault();
});

现在,要查看文本框中已有多少个逗号,我们可以使用正则表达式。如果没有匹配项,match函数将返回null而不是空数组,因此我们必须检查它。

$("input").keypress(function(event) {
    var matches = $(this).val().match(/,/g);
    var count = 0;
    if (matches)
        count = matches.length;
    console.log(count);
});

最后,我们需要能够检查用户是否输入了昏迷状态。 event对象将具有名为which的属性,该属性包含输入字符的键代码。通过一些探索,您可以发现昏迷的关键代码是44。

$("input").keypress(function(event) {
    if (event.which == 44)
        event.preventDefault();
});

所以如果我们把它们放在一起:

$("input").keypress(function(event) {
    var matches = $(this).val().match(/,/g);
    var count = 0;
    if (matches)
        count = matches.length;

    if (count >= 2 && event.which == 44)
        event.preventDefault();
});

http://jsfiddle.net/4wn5W/

答案 2 :(得分:0)

$(document).ready(function(){
    $('#textbox').keypress(function(e){
        var text = $(this).val();
        if(text.split(',').length>3){
             return false;
        }else if(e.which==44&&text.split(',').length>2){
           return false
        }
    });
});

小提琴:

http://jsfiddle.net/L4X4C/