问题描述:

$('.licensetable :text').live('keydown', function (event) {

if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105) && (event.keyCode != 8)) {

event.preventDefault();

}

});

I only allow numbers. This works. But if i log

$(this).val().length

Its obviously "one step after". If i bind the keyup event, i get the correct number. But then i cant disable the keypress event. My goal is to disable the input after a certain amount of numbers has been entered. Hope you get the idea. Thanks

网友答案:

You can simply set the attribute maxlength='X' on the input field.

See it in action.

网友答案:

You could use the maxlength attributes of the input field so that the user can't enter more characthers than those (hope i understood your question correctly)

Then if you want to disable the input when the maxlength is reached you can do:

$('input:text').live('keydown', function(event) {

    if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105) && (event.keyCode != 8)) {
        event.preventDefault();
    }
    var maxlength = $(this).attr('maxlength');
    if (this.value.length == maxlength) {
        $(this).prop('disabled', true);
    }

});

Fiddle here: http://jsfiddle.net/nicolapeluchetti/2YmAG/

相关阅读:
Top