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) %>");
});
4
  • 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"). Commented Oct 3, 2020 at 9:49
  • I'm trying to change an image on change of a select Commented Oct 3, 2020 at 9: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. Commented Oct 3, 2020 at 9:59
  • I've added additional details to my question Commented Oct 3, 2020 at 10:08

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I have never actually used select2 so YMMV. I based the JS off stackoverflow.com/questions/22261209/…
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);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.