Here is my full code if anyone is interested. This code Observes the
text_field_tag “search” every 2 seconds and if there is a change in
the value it triggers a search automatically. The submit button can
now be done away with I think. I might add “:autocomplete =>
“off”, :onKeyPress=>“return disableEnterKey(event)”) %>” to the
text_field_tag to disable the return key, not sure.
In my index.html.erb I have:-
<h1>Listing homepages</h1>
<div id = "testsearch">
<%=render :partial => 'homepage'%>
</div>
<%= form_tag homepages_path, :method => 'get', :remote => true do
%>
<%= label_tag(:search, “Search for:”) %>
<%= text_field_tag :search, params[:search]%>
<%= submit_tag “search”, :name => nil %>
<%end%>
<%= set_focus_to_id 'search' %> // I have a helper
“set_focus_to_id”
<script>
document.observe("dom:loaded", function() { // ensures the page
is loaded first
new Form.Element.Observer( // Observes
the text_field_tag every 2 seconds
‘search’,
2,
respondToChange //refrences the function
in the Layout
) // on a
change in search calls respondToChange
});
<%= link_to ‘New Homepage’, new_homepage_path %>
In my application Layout head I have:_
<script>
function respondToChange() {
$('search').up('form').submit() // The ".up finds the
form in the DOM"
};
</script
In my controller#index I have:-
def index
@homepages = Homepage.search(params[:search]) //".search method
is in the Model"
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @homepages }
format.js
end
end
In my Model I have:-
def self.search(search_item)
if search_item
self.where('section LIKE ?', "%#{search_item}%") //Handles
the ajax call.
else
self.all //Handles
the html call on startup.
end
end
In the helper I have:-
def set_focus_to_id(id)
javascript_tag("$('#{id}').focus()");
end
In the “_homepage” partial I have:-
<table>
<tr>
<th>Id</th>
<th>Section</th>
<th>Link</th>
<th>Description</th>
<th></th>
<th></th>
<th></th>
</tr>
<% for homepage in @homepages %>
<tr>
<td><%= homepage.id %></td>
<td><%= homepage.section %></td>
<td><%= homepage.link %></td>
<td><%= homepage.description %></td>
<td><%= link_to 'Show', homepage %></td>
<td><%= link_to 'Edit', edit_homepage_path(homepage) %></td>
<td><%= link_to 'Destroy', homepage, :confirm => 'Are you
sure?’, :method => :delete %>
<%end%>
</table>
And in the index.js.erb I have:-
$('testsearch').update("<%= escape_javascript(render :partial =>
‘homepage’) %>");
If anyone has any comments on how I could improve this please contact
me or say so.