1

I can't retrieve the id of my form which is found in a PHP loop the last one between works but not the following ones

JavaScript

$(document).ready(function() {
  $('#sendDelete').on('click',function(){
    var id = $(this).data("id");
    alert (id);
  });
});

PHP

while ($last_data = $req_last_data->fetch(PDO::FETCH_ASSOC)){
    $last_id = $last_data['id'];?>
    <tr><?php
        if (!empty($_SESSION['us_id']) && $_SESSION['us_idRang'] <= 2){?>
            <td>
               <form id="formDeleteQuantity-<?= htmlspecialchars($last_id, ENT_QUOTES, 'UTF-8');?>" method="post" action="../controller/deleteEnter.php" role="form">
                 <button type="button" id="sendDelete" class="btn btn-dark btn-index" value="delete" data-id ="<?= htmlspecialchars($last_id, ENT_QUOTES, 'UTF-8');?>">Supprimer</button>
                </form>
            </td><?php
        }?>
    </tr><?php
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
sairus
  • 21
  • 2
  • 1
    `id`s need to be unique in a document. You have multiple `id="sendDelete"`. Use a class instead – brombeer Jul 31 '21 at 06:31
  • What @brombeer says is true. Also you wanna use `$(this).data("data-id")` in your js to sense the value. – Sherif Jul 31 '21 at 07:38

1 Answers1

0

You're selecting specific id, which is wrong because the code is supposed to work for many elements (button)

IDs are supposed to be unique in the document.

So you have to select based on something that all the button element have in common. So you can do this

$(document).ready(function() {
  $('button').on('click',function(){
    var id = $(this).attr("data-id");
    alert (id);
  });
});

Or You can also give those buttons same class name eg btn_for_id

So you'll modify the JS code like

$(".btn_for_id").on('click', function (){

})

You should also consider concatenating a unique number to the buttons IDs just as you have done for the forms so that they'll be unique.

ket-c
  • 211
  • 1
  • 10