Clearing Search text_field_tag In Rendered Form on Submit

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


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


    <%= 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 %>


    where("(foo) LIKE ?", "%#{search}%")


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

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


as a function in the

<body onload...

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


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!

1 answer

  • answered 2018-03-13 21:47 Foo Bar Zoo

    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.