Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ajax call after x characters

Tags:

jquery

ajax

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 there any way to prevent additional ajax calls after the 5 character limit?

html

<input type="text" value="" id="billZipCode" name="billZipCode" class="smallInput coreAddrBill" maxlength="5">

javascript

//show city/state on input maxlength
$("input#billZipCode").live("keyup", function( event ){
    if(this.value.length == this.getAttribute('maxlength')) {
        if ($(this).valid() == true ) {
            zipLookup(this, "USA");

        }
    }
});
like image 935
Jason Avatar asked Jan 28 '26 19:01

Jason


1 Answers

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.

like image 122
jackwanders Avatar answered Jan 30 '26 09:01

jackwanders



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!