AnthonyGalli.com AnthonyGalli.com - 6 months ago 10
Ruby Question

How to pass attribute data by clicking on image?

How to pass attribute data by clicking on an image:

# Something like this I would imagine
<%= f.select '1.png', ranking: 1 %>
# or
<%= f.image_tag '1.png', ranking: 1 %>


Attempts Based Upon @Tadman

1

<%= f.hidden_field(:ranking, id: 'ranking') %>
<%= image_tag('1.png', data: { rank: 1 }, class: 'image-clicker') %>
<%= image_tag('2.png', data: { rank: 2 }, class: 'image-clicker') %>
<%= image_tag('3.png', data: { rank: 3 }, class: 'image-clicker') %>
<%= image_tag('4.png', data: { rank: 4 }, class: 'image-clicker') %>


2

<%= f.hidden_field(:ranking, id: 'image_ranking') %>
<%= image_tag('1.png', data: { image_ranking: 1 }, class: 'image-clicker') %>
<%= image_tag('2.png', data: { image_ranking: 2 }, class: 'image-clicker') %>
<%= image_tag('3.png', data: { image_ranking: 3 }, class: 'image-clicker') %>
<%= image_tag('4.png', data: { image_ranking: 4 }, class: 'image-clicker') %>


3

<%= f.hidden_field(:image_ranking, id: 'image_ranking') %>
<%= image_tag('1.png', data: { ranking: 1 }, class: 'image-clicker') %>
<%= image_tag('2.png', data: { ranking: 2 }, class: 'image-clicker') %>
<%= image_tag('3.png', data: { ranking: 3 }, class: 'image-clicker') %>
<%= image_tag('4.png', data: { ranking: 4 }, class: 'image-clicker') %>

Answer

Normally you do this with the unobtrusive JavaScript available in Rails:

<%= f.hidden_field(:image_ident, id: 'image_ident') %>
<%= image_tag('1.png', data: { ident: 1 }, class: 'img-clicker') %>

Then you can trigger it with jQuery:

$('.img-clicker').click(function() {
  $('#image_ident').val($(this).data('ident'));
});

Idea here is you can have a hidden field to capture your selection and each image when clicked transfers its data value over. You can even add class information to make the selected image look different afterwards, up to you.

Comments