1

I'm trying to create a simple buddy list for a web application. I'm looping through an SQL table to retrieve the current user's buddy list. Each row in the table has a button to display a modal of the selected user's ID. The current issue I'm having is that it's only showing the modal for the last user in the list, for everyone else it doesn't pop up. I need the modal to pop up for each user I click on and display that user's ID. Example: enter image description here

Here is the code I have so far:

HTML/PHP:

<?php
// Full SQL retrieval omitted above 
$buddyUid = '';
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
    $buddyUid = $row['buddy_uid'];
                                                                   
    echo "<tr>";
    echo "<td> <input type='checkbox'></td>";
    echo "<td>" . $buddyUid . "</td>";
    echo "<td> <button type='button' onclick='javascript:selectBuddy($(this)); ' data-bs-toggle='modal' data-bs-target='#modal-" . $buddyUid . "'><i class='fas fa-share-square'></i></button></td>";
    echo "</tr>";
}

?>

<!-- Modal -->
<div class="modal fade" id="modal-<?=$buddyUid?>" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
         <div class="modal-content">
             <div class="modal-header">
                  <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
                  <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
              </div>
              <div class="modal-body">
                  <?= $buddyUid?>
               </div>
               <div class="modal-footer">
                   <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                   <button type="button" class="btn btn-primary">Save changes</button>
                </div>
           </div>
       </div>
   </div>

Javascript:

function selectBuddy(buddy) {
    $('#modal-' + buddy).modal('show'); 
}
kdarling
  • 59
  • 2

1 Answers1

0

$(this) refers to the element in the DOM to which the onclick attribute belongs:

in your case to get only buddy_id just change onclick event

from this

...onclick='javascript:selectBuddy($(this));'...

to this

...onclick='javascript:selectBuddy(".$buddyUid.");'...

also change your Modal id from

<div class="modal fade" id="modal-<?=$buddyUid?>" ...

to

<div class="modal fade" id="modal-buddy" ....

then javascript code like this

function selectBuddy(buddy) {
    $('#modal-buddy').find('.modal-body').html(buddy);
    $('#modal-buddy').modal('show'); 
}
adam
  • 347
  • 2
  • 7