Saranga
Saranga

Reputation: 520

limit html textbox length

I've HTML textbox and I'll prevent adding characters using regex. This is my code:

$("#CardNo").keypress(function (e) {

    if (e.keyCode == "13") {
        $("#CardAmount").focus();
    }
    else {
        $(this).val($(this).val().replace(/[^0-9]/g, ''));
        if ((event.which < 48 || event.which > 57)) {
            event.preventDefault();
        }
    }
});

I need to add another regex part for limiting textbox's length to 6, how can I do that?

Upvotes: 1

Views: 257

Answers (2)

Riad
Riad

Reputation: 3870

As you are using jquery, besides HTML you can do it with the following also:

$("#CardNo").attr("maxlength", 6);

OR

if( $("#CardNo").val().length() > 6 ){
    // remove characters and show alert...
}

Upvotes: 0

TGH
TGH

Reputation: 39278

You can do this

<input type="text" maxlength="6" />

It also works for textareas if that is needed

<textarea maxlength="6">

</textarea>

Upvotes: 7

Related Questions