I am unable to append image src using the closest img tag.
When autocomplete option select i want to populate the image for that row
HTML :
<td>
<div>
<img class="participantphoto" src="images/author2.jpg" width="50" />
<input placeholder="Type a letter to search students" class="form-control searchStudent formbottom" name="student[0][name]" type="text" autocomplete="off">
</div>
</td>
JS :
$(document).on("focus keyup", "input.searchStudent", function (event) {
$(this).autocomplete({
source: 'gdcontroller.php?action=search',
select: function (event, ui) {
console.log(ui);
event.preventDefault();
this.value = ui.item.label;
// line below fails
$(this).parent().closest( ".participantphoto" ).attr("src",ui.item.profile_pic);
},
focus: function (event, ui) {
event.preventDefault();
this.value = ui.item.label;
}
});
});
That not work because the img .participantphoto
is not a parent of the input .searchStudent
.
You should go to the closest div using .closest('div')
then find the img tag with class participantphoto
using .find(".participantphoto")
and finally set the attribute src
:
$(this).closest('div').find(".participantphoto").attr("src",ui.item.profile_pic);
Or you could use .siblings()
instead :
$(this).siblings(".participantphoto").attr("src",ui.item.profile_pic);
Hope this helps.
closest
starting from the input
won't find the img
, because the img
isn't an ancestor of the input
, it's a sibling.
As it's the only img
sibling, $(this).siblings("img")
finds it:
$(this).siblings( "img" ).attr("src",ui.item.profile_pic);
or if you want to use the class:
$(this).siblings( ".participantphoto" ).attr("src",ui.item.profile_pic);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.