<select id="filter" >
<option value="<%= profile_path(@profile)%>" > <%= link_to "Weekly", profile_path(@profile), class: 'form-control'%> </option>
<option <%= params[:daily] ? "selected" : "" %> value="<%= profile_path(@profile,:daily => "true")%>"> <%= link_to "Daily", profile_path(@profile,:daily => "true"), class: 'form-control' %></option>
</select>
I want to give link to option field of select. It doesnot work. ANy other ways?
CodePudding user response:
I don't think link_to
is good inside option tag since as soon the user click the option to select it will be redirect to specified path which you may not want instead you can try using title
attribute on option tag.
Try this:
options = [
[
"Weekly",
profile_path(@profile),
{ :title => profile_path(@profile) }
],
[
"Daily",
profile_path(@profile, :daily => "true"),
{ :title => profile_path(@profile, :daily => "true") }
]
]
<%= select_tag :filter, options_for_select(options, "Daily") %>
CodePudding user response:
Using a link inside an option tag is a horrible idea since its invalid HTML. In fact <option>
tags cannot contain any other elements. The permitted contents are "Text, possibly with escaped characters (like é).".
<select>
<option>I just broke the internets <a href="">click me</a></option>
</select>
The link won't even be clickable either as the browser will most likely just ignore the <a>
tag.
What you most likely actually want to is create a form that sends GET requests:
<%= form_with(url: profile_path) do |form| %>
<%= form.label :daily %>
<%= form.select :daily, ["true", "false"], class: 'instant-submit' %>
<%= f.submit "View profiles" %>
<% end %>
If you want the form to submit as soon as the user changes the select you need to use JavaScript to add a change event handler.
const elements = document.querySelectorAll('.instant-submit');
elements.forEach((element) =>{
element.addEventListener('change', (event) => {
event.target.form.requestSubmit();
});
});