jQuery add - 到输入,但只添加两次

jQuery add - to input but only add twice

本文关键字:添加 两次 add 输入 jQuery      更新时间:2023-09-26

我这里有这个小脚本...它每 4 个字符后添加一个"-",但我需要它不要在 12 个字符后添加 - 。

$(function(){
$("#promo").keyup(function(){
    var $this = $(this);
    if ((($this.val().length+1) % 5)==0){
        $this.val($this.val() + "-");
        }   
    });        
});

但它在 12 个字符的末尾添加一个"-",尽管我的字符限制为 14。

我这里有一个JSFiddle

我将如何防止这种情况发生?

maxlength属性不会阻止您使用Javascript修改<input>值。

您仍然可以添加检查:

$(function(){
    $("#promo").keyup(function(){
    var $this = $(this);
    if ((($this.val().length+1) % 5)==0 && $this.val().length() < $this.attr("maxlength")){
      $this.val($this.val() + "-");
    }   
  });        
});

您可以在 if 中添加以下内容:

if ($this.val().length > 12) {
    return false;
}

代码建议(使用较少的jQuery):

$(function () {
    $("#promo").keyup(function () {
        if (((this.value.length + 1) % 5) == 0) {
            if (this.value.length > 12) {
                return false;
            }
            this.value += "-";
        }
    });
});

在这里演示

你可以

简单地使用 &&AND 运算符,并使其成为一个条件,如果 val.length 大于 11,则什么都不会发生

$(function(){
    $("#promo").keyup(function(){
        var $this = $(this);
        if ((($this.val().length+1) % 5)==0 && $this.val().length <=11){
            $this.val($this.val() + "-");
            }   
        });        
    });

http://jsfiddle.net/sAu32/3/

我没有

看小提琴,而是;

$(function(){
    $("#promo").keyup(function(){
    var $this = $(this);
    if ((($this.val().length+1) % 5)==0 && $this.val().length <= 12){
        $this.val($this.val() + "-");
        }   
    });        
});
$(function(){
    $("#promo").keyup(function(){
        var $this = $(this);
        if($this.val().length<14){
        if ((($this.val().length+1) % 5)==0){
            $this.val($this.val() + "-");
            }   
        }
        });        
    });

给你。

小提琴更新在这里