I want to use a select menu to redirect to another page but when I select 'Home' it doesn't redirect me to the main page. Nothing happens...
<select>
<option>Select a menu</option>
<opt开发者_运维百科ion><%= link_to 'Home', '/' %></option>
</select>
Thank you for your help.
You can't put a link inside a SELECT tag. This is a limitation of HTML, not Rails.
What you should do instead is something like this:
<%= select_tag(:menu_select, options_for_select([ 'Home', '/' ])) %>
Then you need to ensure that when the new link is selected, the page is loaded. This can be done with jQuery using something like this:
$('#menu_select').bind('change', function() { window.location.pathname = $(this).val() });
When the form selection is changed, the new URL is loaded.
The link_to
helper outputs an HTML hyperlink which is not going to work when nested within an option
element. You should change your options so that they have this format:
<option value="/">Home</option>
Then you could have some JavaScript that observes the onchange
event of the dropdown and sets the document.location.href
to the value of the selected option. This will perform the redirect.
Alternatively, you could have a Go submit button next to the dropdown that submits the form and then have Rails perform a server-side redirect to the page for the selected option using the redirect_to
helper.
This will also work:
<select onChange="if(this.selectedIndex!=0) self.location=this.options[this.selectedIndex].value">
<option value="/">Home</option>
</select>
精彩评论