ajax call after x characters

前端 未结 3 593
感动是毒
感动是毒 2021-01-21 01:42

I have an ajax call triggering on the maxlength of an input. However, it continues to trigger if a user continues to enter characters (because they count as a keypress). Is ther

相关标签:
3条回答
  • 2021-01-21 01:46

    Use a boolean variable to know if a call has already been triggered (init it to false, assert it is still false before making a call, and set it to true when you make the call).

    0 讨论(0)
  • 2021-01-21 02:05

    Set a .data attribute on the field:

    //show city/state on input maxlength
    $("input#billZipCode").live("keyup", function( event ){
    
        if(this.value.length == this.getAttribute('maxlength')) {
            if(!$(this).data('triggered')) {
                // set the 'triggered' data attribute to true
                $(this).data('triggered',true); 
                if ($(this).valid() == true ) { zipLookup(this, "USA"); } 
            }
        } else { $(this).data('triggered',false); }
    
    });
    

    Move the assignment inside the second if statement if you want to keep running this until the zipcode is valid.

    0 讨论(0)
  • 2021-01-21 02:08

    Try this:

    var ready = true;
    $("input#billZipCode").on("keyup", function( event ){
        if(this.value.length == this.getAttribute('maxlength')) {
            if ($(this).valid() && ready) {
                zipLookup(this, "USA");
                ready = false;  
            }
        }
    });
    
    0 讨论(0)
提交回复
热议问题