Clearing Search text_field_tag In Rendered Form on Submit

Diane Source

I am using Rails 5.1 to create a simple search that uses a single text field in a form that gets data from a SQLITE3 DB and returns the data in a table on a new HTML page. The search form is a rendered form which passes the value of the search to the controller

index.html.erb

<%= render 'search', foo: @foo %>

_search.html.erb

<div>
    <%= form_tag(search_home_index_path, :method => 'get', id: 'search_form') do %>
        <%= text_field_tag :search, params[:search], id: 'search_field', placeholder: "Search", :required => 'required'%>
        <%= submit_tag("Search", :class => "button", :name => nil) %>
    <% end %>
</div>

application_record.rb

def self.search(search)
    where("(foo) LIKE ?", "%#{search}%")
end

home_controller.rb

def search
   if params[:search]
   @foo = Foo.search(params[:search]).order("id ASC")
       else
   @foo = Foo.all.order("id ASC")
   end
end

The search is working fine and returning values. However, (and I believe it's because I am rendering the same form on multiple pages), when the search returns, the text_field_tag value retains the search criteria entered on the original page and populates that same value in the text_field_tag on the new page. I have attempted to use JavaScript to clear the text_field_tag by using

document.getElementById('search_field').value='';

as a function in the

<body onload...

but it is not working - the text_field_tag retains the value. I have also tried using

document.getElementById('search_form').reset();

but this ends up sending a blank value in my search variable and returns all the items in the database.

I have seen some references to placing the code for the field value in a Coffee script, but I'm not sure how to implement this (I've been coding Ruby for a grand total of about 2 months now).

Any suggestions would be appreciated!

javascriptruby-on-railsrubyhtml5

Answers

answered 6 months ago Foo Bar Zoo #1

Actually you are the one setting this value in your form. You can set it to nil, like so;

<%= text_field_tag :search, nil, id: 'search_field', placeholder: "Search", :required => 'required'%>

The documentation for the text_field_tag can be found here.

comments powered by Disqus