july
july

Reputation: 33

How to alert when I input more that limit length?

I create an input and it's support number only and maxlength only 3 digits. when i type more than 3 digits I want it alert right away without press any button. How to do that in jQuery?

HTML

<input type="text" name="txtprice" id="txtprice" class="input-xlarge" maxlength="3" required />&nbsp;<span id="errmsg"></span> 

Javascript

$(document).ready(function () { 
    //called when key is pressed in textbox
    $("#txtprice").keypress(function (e) { 
        //if the letter is not digit then display error and don't type anything 
        if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) { 
           //display error message 
           $("#errmsg").html("Must input numbers").show().fadeOut("slow").css("color","red"); 
           return false; 
        }
    }); 
});

Upvotes: 1

Views: 21844

Answers (1)

Angry 84
Angry 84

Reputation: 2995

What your asking is not really... valid, if you set a max length and want an alert once it exceeds this limit.. Well that should not happen.

Try this fiddle: http://jsfiddle.net/0d20e24n/

$( "#myinput1" ).on('input', function() {
    if ($(this).val().length>3) {
        alert('you have reached a limit of 3');       
    }
});

$( "#myinput2" ).on('input', function() {
    if ($(this).val().length>=3) {
        alert('you have reached a limit of 3');       
    }
});

The first should never alert, the second will only when you have typed 3 characters?

Upvotes: 4

Related Questions