I cannot figure out how to compress this code to make it DRY. It works fine with different elements or when repeating code, but I want to keep it clean. This is the html:
<div class = "face left">
<img src = "/images/faces/empty.jpg"><br>
<select>
<option value="empty">Select one</option>
<option value="ab18e97e6c64f8db588e95772daf51b4">Takeshi</option>
<option value="d27b579c196202648ba7c4b1904e8e20">Osuka</option>
</select>
</div>
<div class = "face right">
<img src = "/images/faces/empty.jpg"><br>
<select>
<option value="empty">Select one</option>
<option value="ab18e97e6c64f8db588e95772daf51b4">Takeshi</option>
<option value="d27b579c196202648ba7c4b1904e8e20">Osuka</option>
</select>
</div>
The not working jquery I've got so far:
$('.face').children('select').change(function()
{
$(this).
siblings('img').
replaceWith('<img src = "/ajax/faces/' + $(this).siblings('select option:selected').attr('value') + '">');
});
I want to achieve that, when I change the select, the img of that div gets replaced for a new one (with the src dynamically created from the value of the choosen option). I can get it to kind of work if I do this (deleting the $(this).siblings
):
$('.face').children('select').change(function()
{
$(this).
siblings('img').
replaceWith('<img src = "/ajax/faces/' + $('select option:selected').attr('value') + '">');
});
But with that code I can only have one 'face', and I actually want two. So, how can I modify my jquery code to replace it's sibling <img>
and not to affect other ones? The first code doesn't work because it tries to find the image /ajax/faces/undefined
.