0

I have a several images like this:

<div class="attribImg"><img data-id="9" src="images/attributes/black.jpg" alt="Black"></div>
<div class="attribImg"><img data-id="3" src="images/attributes/red.jpg" alt="Black"></div>
<div class="attribImg"><img data-id="7" src="images/attributes/green.jpg" alt="Black"></div>
<div class="attribImg"><img data-id="8" src="images/attributes/blue.jpg" alt="Black"></div>

... and a hidden data field like this:

<input type="hidden" id="id[1]" name="id[1]" value="1">

I am looking for the correct way to change the value of the hidden input on click of the images based on what is set with data-id in the images.

user2924019
  • 1,983
  • 4
  • 29
  • 49

2 Answers2

0

Using jquery, this can be achieved like this:

   $('.attribImg').on('click', function () {
    var value = $(this).children('img').data('id');
    alert(value)
    $('#id').val(value);
});

UPDATE: The reason the value will not be set is because you have used [] in the id name which is reserved. You are only permitted to use letters(Aa-Zz),digits(0-9),hyphens(-), underscores(_) or colons(:) in that order. There is a good explaination here

WORKING EXAMPLE

Community
  • 1
  • 1
Aditya
  • 1,241
  • 5
  • 19
  • 29
0

Something similar to the below maybe:

$("input:image").each(function(){
    $(this).click(function(){
        $("#id[1]").val($(this).attr('data-id'));
    });
});
Matthew North
  • 553
  • 5
  • 20