Anoel
Anoel

Reputation: 1063

Submit link inside text field with Rails

I have a simple search form with Rails 3.1 and instead of having a submit button, I want a magnifying glass image that when you click on it, is a link to submit the form inside the text box (text_field_tag). An example would be in the Firefox browser, the input box with all the search engines. I tried googling how to do it to no success. So far I have this:

 = form_tag("/search", :method => "get", :class => "search-forum") do
  = label_tag "Search for:"
  = text_field_tag :search
  = submit_tag "Search", :class => "search-submit"

What's the best way to accomplish this?

Upvotes: 0

Views: 507

Answers (1)

Alfonso
Alfonso

Reputation: 759

Don't know if i understood well, tell me if it is no what you are looking for.

Instead of using the submit button you want to perform the submit by clicking on an image or another element that is inside the text field. To acomplish that you can use unobtrubsive javascript using jquery and ajax, in this case you don't need a form:

suppose this is the html you have for the text_field

<input id="search_bar" type="text" placeholder="Search..." name="q">
<span class="search-image"></span>

Now to perform the search all you need is something like this (in a js file):

$(document).ready(function() {
$(".search-image").click(function(){
  var query = $('#search_bar').val() # Get the text on the text field
  $.get('/route?q=' + query, function(data){
    #Perform some actions with the data returned by the server
    $('#some_container').html(data)
  }).success(function(){
     #Here you can perform other actions if the request is successful
     alert('successful request')
  }).error(function{
    #In case the request fail
    alert('request failed')
  })
});
}

Upvotes: 1

Related Questions