8

Is there an equivalent to the Rails/Prototype observe_field method using jQuery without jRails?

I am doing a search-as-you-type with 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)") %>

Rob W
  • 341,306
  • 83
  • 791
  • 678
Mark Richman
  • 28,948
  • 25
  • 99
  • 159

2 Answers2

10

Using jQuery, you'd need to use a selector, something like this should work

$("#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
  });
});

Response to comment

If you want to react to keyup, then replace the first line with

$("#search").bind("keyup", // etc...
Jarrett Meyer
  • 19,333
  • 6
  • 58
  • 52
  • Thanks, but this looks like it will only work when the search box loses focus. I'm looking for a search-as-you-type functionality. – Mark Richman Jan 24 '10 at 16:09
  • Is it possible to add a "delay" to this so it doesn't call after every keyup, but instead waits till the user pauses for a few hundred milliseconds? – Brian Armstrong Apr 09 '10 at 23:21
  • @JarrettMeyer, when I do .html() the whole form gets rendered as raw html in the browser can you tell what might the issue be? – Clone Nov 15 '13 at 16:51
7

Try this:

https://github.com/splendeo/jquery.observe_field

Andy
  • 1,801
  • 3
  • 22
  • 33