I’ve tried to get the second id of the div to delete a product, but whenever I list the "DVD product" in PHP, I just can get the first one. The second forward isn’t work. It only works when I delete the first. How can I fix that?
<?php foreach($dvdLists as $key => $dvdList) { ?>
<div class="product-dvd" id="<?= $dvdList->id_dvd ?>">
<input class="delete-checkbox" type="checkbox" name="checkDvd">
<p> <?= $dvdList->sku ?> </p>
<p> <?= $dvdList->name ?> DVD </p>
<p> <?= $dvdList->price?> $ </p>
<p> Size: <?= $dvdList->size ?> MB </p>
</div>
<?php } ?>
$('#delete-product-btn').click(function(){
if($("div.product-dvd > input.delete-checkbox").is(':checked')) {
var getId = $('[class="product-dvd"]').attr('id');
alert('your id='+getId);
}
});
3
Answers
First you need to go through all the divs and get the selected IDs. You can delete them one by one, or you can delete them collectively by collecting the IDs and sending them to the backend at once.
The issue is that
.attr()
only evaluates the first element.Also note that
.is()
will return true if at least one element matches the condition, so your current code ends up with all checkboxes if just one box is checked.I think you have two options here, either select all
div.product-dvd
and then filter by checked checkbox or select all checked checkboxes and the go up to thediv.product-dvd
.To select all
div.product-dvd
and then filter by checked checkbox, use.has()
:To select all checked checkboxes and the go up to the
div.product-dvd
, use.closest()
:You can use eq function and pass the index 1 in this case to get second element.