Reputation: 1717
I need to take the data-value from the image and put it on the hidden fields without using the hidden field's id.
Edit: I can't use the id's because the set repeats with a different Id.
<div class="optionImageSelection">
<input type="hidden" id="hdnIn">
<ul>
<li>
<img src="iamge1.jpg" data-value="val1" class="optionImageSelect">
</li>
<li>
<img src="image2.png" data-value="val2" class="optionImageSelect">
</li>
</ul>
</div>
<div class="optionImageSelection">
<input type="hidden" id="hdnIn2">
<ul>
<li>
<img src="iamge3.jpg" data-value="val3" class="optionImageSelect">
</li>
<li>
<img src="image4.png" data-value="val4" class="optionImageSelect">
</li>
</ul>
</div>
The jQuery:
function OptionImage(image) {
this.selectImage = function () {
//this works but it needs to be generic.
var hdnSelector = $("#hdnIn");
//this doesn't work but it's what I need
//var hdnSelector = $(image).parents('input:hidden:first');
$(hdnSelector).val($(image).attr("data-value"));
alert($(hdnSelector).val());
};
}
$(document).ready(function () {
$(".optionImageSelect").click(function () {
var oi = new OptionImage($(this));
oi.selectImage();
});
});
Js fiddle: http://jsfiddle.net/p4pMg/1/
Thank you.
Upvotes: 1
Views: 859
Reputation: 55750
Instead of
var hdnSelector = $("#hdnIn");
you can use this selector
var hdnSelector = $(image).closest('ul').prev('input')
You can use a combination of closest
and prev
Upvotes: 1