Passing a javascript variable to Ruby in a combo box nav
Updated Example
I am using a Select Box as a nav. When I select an item, I would like to be redirected to that page.
= select (@organization, "tabs", @o开发者_JS百科rganization.tabs.collect { |t| t.title }, {} { :onchange => "escape_javascript(#{ render edit_organization_tab_path(@organization, this.value)})"} )
So this example does not work because I am not sure how to pass a Javascript variable to Ruby
Is it possible to do this entirely in Ruby? Or do I have to use jQuery?
If you're using jQuery, you can do it with something like this:
= select(@organization, "tabs", @organization.tabs.collect { |t| [ t.title, edit_organization_tab_url(t) ] }, { }, :onchange => "window.location.href=$(this).val()")
The value for each item in the select list should be the URL you want to redirect the person to.
I'm not sure what you meant by putting a Rails render call inside a JavaScript block.
Have you considered how this might degrade if the user does not have JavaScript enabled? Ideally the link elements would still be available as regular <a/>
elements so a user could still visit a page without JS. Especially since your select box controls site navigation, I'd recommend a "progressive enhancement" solution and write the markup first without JS, then add in JS behavior on top of it. You may want some CSS and <div/>
elements that resemble a select box but are not literally a select box, this way you have more control over the contents. Couple of other things, as tadman pointed out, redirecting the user in JavaScript boils down to setting window.location
. If you are using jQuery, check the change event which you can attach to selection events in your combobox, and redirect the user as necessary. Finally, using CSS3 border-radius
and other properties, you could create something that looks very similar to a select box, but has much more functionality. You could also find a component like this, googling turned up this example.
You don't need jQuery, but you will need Javascript. Ultimately, you will either need to use (and possibly create) a helper that will create a navigation-ready select box (including the necessary Javascript code) or add event listeners to your select directly in your view (inline or in an included script).
精彩评论