Forgive me if this question has been asked before but I am new to jQuery and am having trouble even describing my problem. I have a loop in a php page that looks something like this:
foreach ($blahs as $blah) {
echo '<p class="title">'.$blah->title.'</p>';
echo '<input/>';
echo '<input/>';
echo '<div class="delete-button"><img /></div>';
}
What I am trying to accomplish is the replacement of .$blah->title. with the phrase “Delete this title?” in the closest preceding <p> element to whichever <div class="delete-button"> is clicked. To do this I have some jQuery at the top of the page like so:
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery(".delete-button").click(function() {
jQuery(this).prev('.title').html("Delete this title?");
});
});
</script>
However, this does not work. If I remove the .prev('.title') it replaces the html of the div so I know its working on some level but I cannot manage to get it to replace the html of the previous <p class="title">. Thanks for your help.
you can take it a step further by wrapping all the items in a common parent and attach a single handler to the parent using
.on()instead of assigning a handler per button. it’s a performance benefit to only have a single handler as opposed to havingXnumber of handlers forXitems in the list.also, seeing the structure of your items, let’s wrap them. it prevents all items from being siblings (thus making an item distinct). then we can just use the
.sibling()method to find the title relative to the button.also, better use lists, they are more semantic.
DEMO