select2 gem remember selected options after search - ruby-on-rails

I have used select2 gem in my rails 6 project to show multiple options to select
<%= select_tag 'skill[]', options_for_select(Course.populate_data, :selected=> "#{params[:skill] rescue nil}"), :prompt => "skill", class: "form-control js-select",id: "js-skill", :style => "width:180px", multiple: "multiple", :style => "width:280px;"%>
I want selectbox to remember my last selections after I submitted the search form
I tried data amd params, but not working for me, can anyone help me with this

I solved the issue, using below code. I was not doing AJAX call, otherwise I would have done this in success response of query
$(".js-select").select2();
if ("<%=params[:skill]%>") {
var a = <%=raw params[:skill]%>
$('#js-skill').select2().val(a).trigger('change');
} else {
$("#js-skill").select2();
}
Posting the answer, if it may help someone

Related

Why drop down list appears behind the box ? Using Simple Form + Select2

I am trying to implement a dropdown list in a simple_form but the collection of emails appears behind the main box. See image below:
I have already tried to play with z-index but failed. I have also tried to add some javascript code according to select2 documentation regarding common problems (https://select2.org/troubleshooting/common-problems ) and also failed.
Ruby slim code is:
.reveal id="doubt-material-#{material.id}" data-reveal=true
= simple_form_for [:student, trail, component, material, material_student, doubt], html: { id: "doubt" }, remote: true do |f|
= f.input :recipient, :collection => %w[contato#witseed.com suporte#witseed.com], label: "#{t 'students.materials.index.questions.form_send_email'}", include_blank: "#{t 'students.materials.index.questions.form_blank_line'}"
javascript:
$('#select2-doubt_recipient-container').select2({
dropdownParent: $('#doubt-material-#{material.id}')
});
Html is:
Does anyone have any idea of whats is going on ?
Thx.

How to implement multi select in a independent table in Rails?

My problem is that I have, for example, Product, Category and ProductCategory.
ProductCategory makes possible for a Product have several Categories
I would like to implement this using Select2 (http://ivaynberg.github.io/select2/) using the select2-rails gem (https://github.com/argerim/select2-rails)
I already know how to relate the models but I can't figure out how to implement the Select2 specific code.
EDIT:
Now I see that my problem was not much about select2, so I added this comment and changed the title hoping that it can help somebody else
Now I see that my problems were not about select2 but to do a multi select.
The code in the _form.html.erb that make it work is this one:
<%= f.label :category_id %>
<%= f.collection_select :category_ids, Category.order(:name), :id, :name, {:selected => #product.category_ids, :include_blank => true}, {:class => 'col-xs-12 col-md-7 padding_15', :multiple => true} %>
I also included :category_ids in the attr_accessible on models/product.rb
And the select2 specific, I included in a .js file
$(document).ready(function() {
$('#product_category_ids').select2();
});
I'm including these links as they helped me but pay attention on the differences depending on the Ruby/Rails versions
http://www.dzone.com/snippets/using-mutiple-collection
http://www.alethe.com/brad/2009/10/multiple-select-list-in-rails/
Just to let you know, unexpectedly, if this collection_select is the last line in my form, some form fields are disabled although there is nothing that states this in the source. Changing the order this problem doesn't exist.
I also don't know why the look is a little different than the other fields (I'm using Bootstrap 3)

Bootstrap Typeahead in Rails

I'm using Bootstrap-sass and formtastic in my Rails application, and I'm not sure why the bootstrap-typeahead feature isn't working.
Form partial:
<%= f.input :tag, :input_html => { :'data-provide' => "typeahead", :'data-source' => '["hello", "hellow", "heaven", "helo", "herr"]' } %>
application.js manifest:
//= require bootstrap-typeahead //typeahead is correctly loaded, checked with firebug
result HTML source code:
<input :data-minLength="2" data-provide="typeahead" data-source="["hello", "hellow", "heaven", "helo", "herr"]"
In the end, I will need to customize typeahead to get the performance I want, but even this simple javascript isn't working for some reason. I cant find anything wrong with the code. Could anyone help me?
UPDATE:
I tried it in the javascript way as follows:
<script> //call typeahead
$(function() {
$('input#type_ahead').typeahead({
'source' : ["hello", "heaven", "heythere"]
});
})
</script>
<%= f.input :tag_list, :input_html => { :id => "type_ahead" }, %> //input tag
And still it seems like typeahead fails to work. i.e) typing in "he" does not get me a dropdown of those three items in the above array. Does anyone have an idea?
I think you need to set html_safe for:
{ :'data-source' => '["hello", "hellow", "heaven", "helo", "herr"]'.html_safe }
Have you called the typeahead() method when your page loads? You need to do something like this;
$(function() {
$('input').typeahead();
})
You'll need to assign a class or id to your input to bind the typeahead to it specifically (Rails probably has assigned an id to it automatically, I'm presuming you've omitted it specifically)
$(function() {
$('input#my-tag-field-with-a-cool-typeahead').typeahead();
})
edit:
The following worked for me. It'll take a bit of modification to the rails part to fit your situation, but this definitely works.
<script>
$(function() {
$('input#type_ahead').typeahead()
}
</script>
<%= text_field_tag :test_type, '', data: {provide: 'typeahead', source: "['hello','heythere','heaven']"} %>

f.select onchange , pass this.value to a ruby variable

I have got this line of code in form:
f.select(:SUB_ASSAY_TYPE, #types, {:prompt => 'Select the Type'}, {:onChange => "alert(this.value)}) %>
What i want to do is to assign the 'this.value' to a ruby variable on onchange event like shown below:
{:onChange => "alert(this.value); #rubyvar = (this.value)" }
I know that's not how it should be done but i have no idea how to do this in ajax or using remote function.
Many thanks for your help
There is no way to set a ruby variable from the client, since its evaluated on your server.
What you need is an Ajax call which renders some new javascript to the client.

RoR select_tag selected value

I'am using select_tag and I want to pass selected value in href :onchange
I couldnt fetch the selected value
Please guide me how to fetch the selected value and pass in href
I'am using following code
<%= select_tag "name",
options_for_select(#user.names.map {|c| [c.firstname,c.id]}),
:onchange =>"document.location.href='/names/value'" %>
In the code in href='/names/**value** at the place of value I have to pass selected value
Thanks
I'm not sure to understand your question but you can try this:
<%= select_tag "name", options_for_select(#user.names.map {|c| [c.firstname,c.id]}),:onchange =>"document.location.href='/names/'+this.value" %>
Thereby, the selected value is used during the onchange event.
Try this
<%= select_tag "name",
options_for_select(#user.names.map {|c| [c.firstname,c.id]}),
:onchange => "document.location.href=/names/ + $(this).value" %>
I think the suggested methods j and kiva would not work because the javascript components are rendered (written to the static html file) at the initial stage, rails is server side, and what is suggested in their posts is more client side.
I achieved it like this ->
add a onchange => myJavaScriptFunction()
and then code the url change in the javascript function()
using pure javascript, no rails involvement.
here's my snippet -
<%= select_tag :clientid, options_for_select(#options),
:include_blank => false,
:onchange => "myfunction(this)"
%>
function myfunction(combo_box)
{
//var combo1 = document.getElementById('clientid');
var value1 = combo_box.options[combo_box.selectedIndex].text;
var value2 = combo_box.selectedIndex;
document.getElementById('session_dump').innerHTML='<hr>'+value2 + '::::=> ' + value1+'<hr>';
}
Hope its useful...

Resources