Ask A Question


You’re not receiving notifications from this thread.

How would I use cookies in a check_box_tag to maintain state between page requests?

Lance Williams asked in General

I've created a multi filter widget using a search_field_tag, and multiple check_box_tags and I can't seem to figure out how to maintain the checked checkboxes state throughout the session. So for instance if a user filters on several checkboxes and then visits a few other pages and returns to the search/filter page all of the filters previously selected are now blank.

I would like to show the filtered/checked state throughout the browser session and clear it out when the browser is closed.

I hope my question clear enough but if it isn't I can provide a better example.

I'm currently using javascript to go back one page i.e history.go(-1) and it keeps things correct if visiting a show page and then back to the search/filter page but I would really want things to be cleaner and maintained through out the session.

Any pointers would be greatly appreciated.

Thanks so much.


Great question! I would say that when you submit the search, you can just save the params to cookies. Something like this:

<%= check_box_tag 'genre', 'rock', cookies['genre'] %>
cookies['genre'] = params[:genre]

And then when you render the form again you can set the checked option to the value of the cookie (like you see here as the 3rd argument of check_box_tag).

You could also write to your cookies using Javascript if you wanted to keep it entirely in JS. You'd have to check the boxes using JS in that case.


Thanks Chris. Yeah I haven't worked that much with cookies even though they've been around forever. I'm currently working on using the Javascript approach which I think will be perfect for maintaining state for the search and checkboxes.

Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 83,038+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.