0

I have a select input where the user can pick a Company. Each company has an image url, I want that when the user click on a select option, the image of the company is added next to select input. Here I want to have the data.id to return it's value so that the url can be generated with the correct image.

In my view I have

<img class="my_img" src="">

<%= select("company", "company_id", Company.all.collect {|p| [ p.name, p.id ] }, { id: "select-company"})%>

In my js.erb file I have

$('#select-company').on('select2:select', function (e) { 
  var data = e.params.data;
  $(".my_img").attr("src", "<%= Company.find(#{data.id}).logo_url(:thumb) %>");
});
user3805610
  • 252
  • 2
  • 13
  • This example just won't work at all. The ERB interpolation happens on the server and it does not actually run javascript. So you will just get a NoMethodError. What is it that you're actually trying to accomplish with this code? (and please don't say "include a javascript variable"). – max Oct 03 '20 at 09:49
  • I'm trying to change an image on change of a select – user3805610 Oct 03 '20 at 09:52
  • Can you add an example of the view and user story? This sounds like you should use data attributes to attach urls to elements in your view. – max Oct 03 '20 at 09:59
  • I've added additional details to my question – user3805610 Oct 03 '20 at 10:08

2 Answers2

2
select("company", "company_id") do
  Company.all.each do |c|
    content_tag(:option, c.name, value: c.id, data: { src: c.logo_url(:thumb) })
  end
end

By passing a block to select you can customize the generation of the option elements and attach a data attribute to the elements.

You can then simply read the data attribute in your event handler:

$('#select-company').on('select2:select', function (e) { 
  var src = $(e.params.data.element).data('src');
  $(".my_img").attr("src", src);
});

None of this really requires the use of js.erb templates.

max
  • 96,212
  • 14
  • 104
  • 165
  • I have never actually used select2 so YMMV. I based the JS off https://stackoverflow.com/questions/22261209/get-custom-data-attribute-in-select2-with-select – max Oct 03 '20 at 10:39
0

Thanks to the answer of @max here is the solution including a selected param and a class.

select("company", "company_id", Company.all.collect {|p| [ p.name, p.id, { 'data-url-path'=>p.logo_url(:thumb) }] }, { selected: params["company_id"] }, { class: "select-company" })
$('#company_company_id').on('select2:select', function (e) {
  var data = e.params.data;
  var src = $('#company_company_id select option[value="' + data.id + '"]').data('url-path');
  $(".my_img").attr("src", src);
});
user3805610
  • 252
  • 2
  • 13