2010-01-24 16 views
8

Esiste un equivalente al metodo Rails/Prototype observ_field che utilizza jQuery senza jRails?Rails observ_field using jQuery

sto facendo una ricerca-as-you-type con will_paginate:

 

<%= observe_field('search', 
        :frequency => 2, 
        :update => 'results', 
        :loading => "Element.show('spinner')", 
        :complete => "Element.hide('spinner')", 
        :url => { :controller => 'foo', :action => 'search' }, 
        :with => "'search=' + escape(value)") %> 

risposta

10

utilizzando jQuery, avresti bisogno di utilizzare un selettore, qualcosa di simile a questo dovrebbe funzionare

$("#search").bind("blur", function() { 
    $("#spinner").show(); // show the spinner 
    var form = $(this).parents("form"); // grab the form wrapping the search bar. 
    var url = form.attr("action"); // grab the URL from the form's action value. 
    var formData = form.serialize(); // grab the data in the form 
    $.get(url, formData, function(html) { // perform an AJAX get, the trailing function is what happens on successful get. 
    $("#spinner").hide(); // hide the spinner 
    $("#results").html(html); // replace the "results" div with the result of action taken 
    }); 
}); 

Risposta al commento

Se si desidera reagire a una chiave, sostituire la prima riga con

$("#search").bind("keyup", // etc... 
+0

Grazie, ma questo sembra che funzionerà solo quando la casella di ricerca perde il focus. Sto cercando una funzionalità di ricerca-come-tu-tipo. –

+0

@ Mark Richman modificato nel post –

+0

È possibile aggiungere un "ritardo" a questo in modo che non richiami dopo ogni keyup, ma invece attende che l'utente si fermi per qualche centinaio di millisecondi? –