Changing an image's ALT value with jQuery
I have a modal form that changes the caption of a photo (paragraph under the image) and I am also trying to change the image's ALT attribute but cannot seem to.
Here is the jQuery I am trying to make work
$(".edit").click(function() {
var parent = $(this).parents('.item');
var caption = $(parent).find('.labelCaption').html();
$("#photoCaption").val(caption);
$("#editCaptionDialog").dialog({
width: 450,
bgiframe: true,
resizable: false,
modal: true,
title: 'Edit Caption',
overlay: {
backgroundColor: '#000',
opacity: 0.5
},
buttons: {
'Edit': function() {
var newCaption = $("#photoCaption").val();
$(parent).find(".labelCaption").html(newCaption);
$(parent).find('img').attr('alt', newCaption);
}
}
});
return false;
});
And the HTML
开发者_开发百科<li class="item ui-corner-all" id="photo<? echo $images['id'];?>">
<div>
<a href="http://tapp-essexvfd.org/gallery/photos/<?php echo $images['filename'];?>.jpg" class="lightbox" title="<?php echo $images['caption'];?>">
<img src="http://tapp-essexvfd.org/gallery/photos/thumbs/<?php echo $images['filename'];?>.jpg" alt="<?php echo $images['caption'];?>" class="photo ui-corner-all"/></a><br/>
<p><span class="labelCaption"><?php echo $images['caption'];?> </span></p>
<p><a href="edit_photo.php?filename=<?php echo $images['filename'];?>" class="button2 edit ui-state-default ui-corner-all">Edit</a></p>
</div>
</li>
The caption is changing like it should.
Thanks
UPDATE
Here is the code for editCaption
<div id="editCaptionDialog" style="display: none;">
<p><strong>Caption:</strong> <input type="text" name="photoCaption" id="photoCaption"/></p>
</div>
Are you sure you're not trying to change the title
attribute?, alt
attribute cannot be seen without disabling images.
This isn't working because, well 2 reasons, look at Ben's answer to see if this is the behavior you want in the first place. Currently you're cloning the jQuery object, this line:
var parent = $(this).parents('.item');
Already returns a jQuery object, so by doing $(parent)
you're cloning it. From the docs:
jQuery(jQuery object)
- jQuery object - An existing jQuery object to clone.
To fix it, instead do this:
parent.find(".labelCaption").html(newCaption);
parent.find('img').attr('alt', newCaption);
Also, I'd change $(this).parents('.item');
to $(this).closest('.item');
to be a bit safer.
精彩评论