0

I have this little script here... It adds a "-" after every 4 characters but i need it to not add the - after the 12 character.

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

But it is adding a "-" at the end of the 12 characters despite my character limit of 14.

i have a JSFiddle here

How would i prevent this from happening?

5 Answers 5

3

maxlength attribute does not prevent you to modify <input> value using Javascript.

You can still add a check:

$(function(){
    $("#promo").keyup(function(){
    var $this = $(this);
    if ((($this.val().length+1) % 5)==0 && $this.val().length() < $this.attr("maxlength")){
      $this.val($this.val() + "-");
    }   
  });        
});
Sign up to request clarification or add additional context in comments.

3 Comments

Wow, just made this in Fiddle, too. Man, there are just too many helpful people on this site! Ha!
thanks @GuillaumePoussel! my jQuery and JS is still very basic!
Sorry it took them a minute to allow me to do that... @GuillaumePoussel
1

You could add this inside your if:

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

Code suggestion (with less jQuery):

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

Demo here

Comments

0

you can simply use the && AND operator and make it a condition that nothing will happen if val.length is greater 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/

Comments

0

I did not look at fiddle but;

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

Comments

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

There you go.

And the Fiddle update here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.