0
votes

I have a rails application where i am trying to add a ruby select tag with jquery select2, the select 2 works perfectly fine. But i want if the user re-vist that page it should show them the value which they previously selected.

This is my code

view.html.erb file

<% if @select2_values.present? %>
   <%= select_tag "select2_name", options_for_select(@select2_values.map { |obj| [obj[:text], obj[:id]] }), multiple: true, class: "form-control select2", id: "resultOf_select2" %>
<% else %>
   <%= select_tag "select2_name", options_for_select([]), multiple: true, class: "form-control select2", id: "resultOf_select2" %>
 <% end %>

When i put binding.pry inside the if statement it properly stops there, and also when i check the console the @select2_values array looks like this

[{ :id 1, :text "some text" },
 { :id 2, :text "some text" },
 { :id 3, :text "some text" },
]

If i remove the multiple : true option it properly display's the first value of the @select2_values array. Can some one help me figure out how can i show all the values with multiple:true option

Any help is appreciated, thanks in advance

1

1 Answers

0
votes

First: you need to store user selected values somewhere... for example localstorage(because if you use sessionStorage this values will be lost)

Second: when user visits your page try to get this user selected values... if there is something then set this values to select2 like this:

$('#mySelect2').val(['1', '2']);

you can found more information about localstorage here:

https://www.w3schools.com/jsref/obj_storage.asp

hope it helps