简体   繁体   中英

How to redirect to another page using a select menu and link_to - Ruby on Rails

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>
    <option><%= 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM