Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails observe_field using jQuery

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)") %>

like image 894
Mark Richman Avatar asked Jan 24 '10 15:01

Mark Richman


2 Answers

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...
like image 145
Jarrett Meyer Avatar answered Oct 02 '22 19:10

Jarrett Meyer


Try this:

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

like image 30
Andy Avatar answered Oct 02 '22 18:10

Andy