2016-01-11 19 views
5

Ho un campo codice postale che ha un evento jQuery onKeyup - l'idea è che una volta inserito completamente il loro codice postale per chiamare un'API Geocoding di Google Maps per ottenere posizione immediatamente basata su questo codice postale.Tweaking sull'evento keyup per chiamare l'API una volta che l'utente ha finito di digitare

Questo codice funziona però mi piacerebbe trovare una soluzione che non sarà idealmente chiamare l'API più volte, ma aspettare e vedere se l'utente ha finito di digitare utilizzando un metodo di aspettare x quantità di tempo e quindi chiamando l'API .

Qualcuno può suggerire il modo migliore per farlo?

$("#txtPostcode").keyup(function() { 
    var postcode = $('#txtPostcode').val().length 
    if (postcode.length >= 5 && postcode.length <= 8) { 
     console.log('length is a valid UK length for a postcode'); 
     // some logic here to run with some way to work out if user has 'finished' typing 
     callGoogleGeocodingAPI(postcode); 
    } 
}); 
+0

Possibile duplicato di [Funzione antirimbalzo in jQuery] (http://stackoverflow.com/questions/27787768/debounce-function-in-jquery) – Piskvor

risposta

6

È possibile utilizzare setTimeout per fare solo la chiamata dopo digitazione è fermato per 250ms - questo è in genere abbastanza tempo tra le sequenze di tasti per consentire l'ingresso a pieno titolo. Prova questo:

var timer; 
$("#txtPostcode").keyup(function() { 
    clearTimeout(timer); 
    timer = setTimeout(function() { 
     var postcode = $('#txtPostcode').val().length 
     if (postcode.length >= 5 && postcode.length <= 8) { 
      console.log('length is a valid UK length for a postcode'); 
      // some logic here to run with some way to work out if user has 'finished' typing 
      callGoogleGeocodingAPI(postcode); 
     } 
    }, 250); 
}); 

è possibile modificare il timeout esatto per soddisfare meglio le vostre esigenze, se pensate che ci sia troppo di un ritardo.

+0

Grazie - questo funziona e richiede modifiche minime! – Zabs

+0

Nessun problema, felice di aiutare. –

+0

Funziona alla grande. Grazie – JimiOr2

1

Ecco un decoratore funzionale che ritarderà l'evento fino all'ultimo tasto premuto. Puoi giocare con il tempo di ritardo per ottenere il miglior feeling. 200 ms è un valore arbitrario.

$("#txtPostcode").keyup(delayEvent(function(e) { 
 
    
 
    console.log('event fired'); 
 
    // this refers to the element clicked, and there is an issue with in the if statement 
 
    // you are checking postcode.length.length which probably throws an error. 
 
    var postcode = $(this).val(); 
 
    if (postcode.length >= 5 && postcode.length <= 8) { 
 
    console.log('length is a valid UK length for a postcode'); 
 

 
    // some logic here to run with some way to work out if user has 'finished' typing 
 
    // callGoogleGeocodingAPI(postcode); 
 
    } 
 
}, 200)); 
 

 
// this is a functional decorator, that curries the delay and callback function 
 
// returning the actual event function that is run by the keyup handler 
 
function delayEvent(fn, delay) { 
 
    var timer = null; 
 
    // this is the actual function that gets run. 
 
    return function(e) { 
 
    var self = this; 
 
    // if the timeout exists clear it 
 
    timer && clearTimeout(timer); 
 
    // set a new timout 
 
    timer = setTimeout(function() { 
 
     return fn.call(self, e); 
 
    }, delay || 200); 
 
    } 
 
}
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" id="txtPostcode">

1

Si può anche provare a utilizzare .blur() al posto di .keyup() nel codice, se non hai provato già.