0

ここにこの小さなスクリプトがあります...4文字ごとに「-」を追加しますが、12文字の後に-を追加しないようにする必要があります。

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

しかし、私の14文字制限にもかかわらず、12文字の最後に「-」が追加されています.

ここにJSFiddleがあります

これを防ぐにはどうすればよいですか?

4

5 に答える 5

3

maxlength<input>属性は、Javascript を使用して値を変更することを妨げません。

チェックを追加することもできます:

$(function(){
    $("#promo").keyup(function(){
    var $this = $(this);
    if ((($this.val().length+1) % 5)==0 && $this.val().length() < $this.attr("maxlength")){
      $this.val($this.val() + "-");
    }   
  });        
});
于 2013-10-17T18:09:48.880 に答える
1

これを次の場合に追加できます。

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 += "-";
        }
    });
});

デモはこちら

于 2013-10-17T18:09:16.893 に答える
0

&& 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/

于 2013-10-17T18:10:00.667 に答える
0

私はフィドルを見ませんでしたが;

$(function(){
    $("#promo").keyup(function(){
    var $this = $(this);
    if ((($this.val().length+1) % 5)==0 && $this.val().length <= 12){
        $this.val($this.val() + "-");
        }   
    });        
});
于 2013-10-17T18:10:07.543 に答える
0
$(function(){
    $("#promo").keyup(function(){
        var $this = $(this);
        if($this.val().length<14){
        if ((($this.val().length+1) % 5)==0){
            $this.val($this.val() + "-");
            }   
        }
        });        
    });

ほらね。

そして、フィドルの更新はこちら

于 2013-10-17T18:10:33.283 に答える