muktoshuvro
muktoshuvro

Reputation: 438

jQuery restrict input range

I have following jQuery script implemented which suppose to restrict input in input form.

<script language="JavaScript">
var inputPlz = $j( "span#spanvertragsnehmer_plz input.plz" );   

function attachEventHandlerToInputNumber(input) 
{
    input.on("keypress", function(key) 
    {
        if ((key.which != 8 && key.which != 0 && (key.which < 48 || key.which > 57)) || inputPlz.val().length > 4) 
        {
            return false;
        }
    });   
}

attachEventHandlerToInputNumber(inputPlz);
</script>

In the following code I can restrict the input but once it goes to 5 digit number I can't edit the number using backspace anymore. Is there anything I missing here ?? Thank you.

Upvotes: 1

Views: 59

Answers (1)

IrkenInvader
IrkenInvader

Reputation: 4050

This statement || inputPlz.val().length > 4 causes the return false; line to execute whenever the input length is 5+, no matter what key is pressed. Backspace is a key like any other thus you cannot backspace after 5+ digits.

If you want to allow backspaces once 5+ digits have been entered you could change that segment to || (inputPlz.val().length > 4 && key.which != 8))

Upvotes: 3

Related Questions