user5835902
user5835902

Reputation:

Filtering by checkbox in rails

I have suffering one issue in my rails application search by checkbox.

This is my checkbox code:

<form action="<%= search_path %>" method="get">
  <%= check_box_tag :title, params[:title] %> Title
  <input type="submit" value="Fielter" />
</form>

This code searching but showing default =on in url like this:

http://localhost:3000/search?title=on

How can I search title like ABC & remove default =on.

I need like this :

http://localhost:3000/search?title=ABC

Thanks

Upvotes: 0

Views: 1517

Answers (2)

Pavan
Pavan

Reputation: 33542

check_box_tag(name, value = "1", checked = false, options = {})

I believe the default value is coming from the params[:title] which you have in the check_box_tag.

Because when you have <%= check_box_tag :title, params[:title] %>, the HTML equivalent will be

<input id="title" name="title" type="checkbox" value="on" /> #assumning the value of params[:title] is on

So the value of checkbox always will be on.

Try changing it to

<%= check_box_tag :title %> Title

Upvotes: 2

Sherlock_HJ
Sherlock_HJ

Reputation: 236

That specific url pattern might be hard to do without javascript, but you can get the desired result (searching on the title only if the checkbox is checked) fairly easily by handling the logic server-side.

Just modify your form to always have the title as a hidden field (so it always gets passed as a parameter on submit) along with the checkbox, which will get passed as a parameter as either 1 or a 0 (true or false) depending on if it's checked or not. Then, you handle the logic in your search path: If the checkbox parameter is true, then search based on the title parameter. if the checkbox is false, then don't use the title parameter.

<form action="<%= search_path %>" method="get">
  <%= hidden_field_tag "title", :title %>
  <%= check_box_tag :use_title %> Title
  <input type="submit" value="Fielter" />
</form>

This will give you a url pattern that looks like this:

http://localhost:3000/search?title="ABC"&use_title="1"
or
http://localhost:3000/search?title="ABC"&use_title="0"

And in the controller action:

if params[:use_title]
  do_something      # Use params[:title] in your search
else
  do_something_else # Don't use params[:title] in your search
end

That should give you the desired behavior.

Upvotes: 0

Related Questions