Select tag : How to use params to set the selected value?
Asked Answered
B

1

6

I have a select tag with 2 options :

 select_tag :type,  options_for_select("<option value = 'produit1'>Produit1</option><option value = 'Produit2'>Produit2</option>", params[:product]), id: "different_option_value_html", onchange: "this.form.submit();", include_blank: "Which products ?"

When one of this options are selected, the form is automatically submit. I would like to keep the params in first position. I mean visible without clicking on the select, at the place of "which products".

Bypath answered 2/11, 2016 at 8:14 Comment(11)
include_blank: params[:product]?Clatter
I already tried this option, it seems the more obvious to me, but it displayed nothing at all.Bypath
may be because params[:product] is nil or empty string?Clatter
I don't think because the param is present in the url, and the products are well filteredBypath
just check what's in params[:product], maybe you want params[:product][:name] or something. Debug the value of params[:product] and make sure it is thereClatter
When I use pry to debug I get : params[:product] = "produit1"Bypath
then it should work just fine. may be add explicit braces { include_blank: params[:product] }Clatter
Yeah that was it ! The only problems is that "which products?" completely disapear and my list look like : "product1, product1, product2" OR "product2, product2, product1". The selected product appear both instead of just being selectedBypath
I'll upvote for your comment for sure. But it's not exactly the answer, see my comment below :)Bypath
select_tag :type, options_for_select("<option value = 'produit1'>Produit1</option><option value = 'Produit2'>Produit2</option>", params[:product], selected: params[:product]), id: "different_option_value_html", onchange: "this.form.submit();", include_blank: "Which products?"Clatter
>> wrong number of arguments (given 3, expected 1..2)Bypath
B
6

I finally change the syntax and it works fine using :options_for_select(:collection, :selected)

So there is my code now :

= select_tag :product,  options_for_select(["Product1", "Product2"], params[:product]), id: "different_option_value_html", onchange: "this.form.submit();", include_blank: "Which product ?"
Bypath answered 2/11, 2016 at 10:10 Comment(1)
Thank you soooo much. Browsed over 10 questions and resources before coming across your answer!Bandwidth

© 2022 - 2024 — McMap. All rights reserved.