开发者

Key up event that executes when 5 characters are entered

开发者 https://www.devze.com 2023-01-24 21:40 出处:网络
I have a function that fires when a user enters in 5 characters in an input field. However, whenever I place additional characters after the 5 has been fulfilled it keeps on firing the event.

I have a function that fires when a user enters in 5 characters in an input field.

However, whenever I place additional characters after the 5 has been fulfilled it keeps on firing the event.

How do I prevent this from occurring?

$(function(){
    var $zipEntry = $('#zipEntry').bind('keyup',function(event) { //bind to key up, doesn't require 
    //make sure 开发者_如何学编程that there are 5 numbers... or length = 5 since numeric only input
    var $this = $(this); // cache $(this)
    
        if ($this.val().length == 5){ // use cached 
            console.log("There are 5 characters!!");
            $this.trigger('zipEntered'); 
        }
    });


Try unbinding the event after you're done listening for it.

if ($this.val().length == 5){
    console.log("There are 5 characters!!");
    $this.trigger('zipEntered');
    $('#zipEntry').unbind('keyup');
}


If i understand you correctly, you need use "greater or equal" instead "equal"

if ($this.val().length >= 5){

Also, why do you use $ in variable names??


Can't the problem be corrected at the source? Put a maxlength on the input field?

0

精彩评论

暂无评论...
验证码 换一张
取 消