Reputation: 1791
I try to change the src value of all of my images under certain condition. but it changes all of them to the first image value, once it changes the first one the rest are the same as first one.
HTML CODE: INPUT:
<label>
<input data-parent=“1” class="attribute" type="checkbox" value=“332” />
CHANGE
</label>
HTML CODE: IMAGES:
//This code is being repeated through the page
<div class="fl-img">
<a href=“Hero_1_url”>
<input class="pictureinput" style="display:none;" type="checkbox" value=“Hero_1” />
//I cant pass the Hero_1 image to jquery based on project structure so I used input to pass
//the Hero_1 value to jquery
<img class="changepicture" src=“Hero_1” alt=“Hero_1” />
</a>
</div>
//There are tens of fl-img divs on repeat based on database (Hero_2, Hero_3,...)
JQUERY:
var checkedValue = $('.attribute:checked').val();
var pictureValue = $('.pictureinput').val();
if (checkedValue == 332)
{
pictureValue = pictureValue.replace("Hero", "00");
$(".changepicture").attr("src", “pictureValue”);
}
This Code works for first picture, but also replace all the pictures with hero value in src to first picture. For example: changes the first Hero_1 to 00_1 but all the other pictures(Hero_2, Hero_3, ...) is being changed to 00_1. I explained as much as I could, If anything is unclear I'm here to explain. Thanks.
Upvotes: 0
Views: 157
Reputation: 87
You should loop through each image instead of first one.
var checkedValue = $('.attribute:checked').val();
if (checkedValue == 332)
{
$(".changepicture").each(function(){
//get parent
var parent = $(this).parent();
var pictureValue = $(parent).find('.pictureinput').val();
pictureValue = pictureValue.replace("Hero", "00");
$(this).attr("src", pictureValue );
})
}
Upvotes: 1
Reputation: 15838
The problem is that you are getting the value of the first image only and using it everywhere
var checkedValue = $('.attribute:checked').val();
var pictureValue = $('.pictureinput').val(); // <--- HERE
if (checkedValue == 332)
{
pictureValue = pictureValue.replace("Hero", "00");
$(".changepicture").attr("src", “pictureValue”);
}
You need to use a different value for each element, you can use the each
function
var checkedValue = $('.attribute:checked').val();
if (checkedValue == 332)
{
$('.pictureinput').each(function(idx, el) {
pictureValue = el.value; // <-- now pictureValue will be different for each image
pictureValue = pictureValue.replace("Hero", "00");
el.nextSibling.src = pictureValue;
}
}
Upvotes: 0