Skip to main content
Ask A Question
Notifications
You’re not receiving notifications from this thread.
Subscribe

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

General • Asked by Lance Williams

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'] %>
#controller
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.


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 30,005+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.