0

I have a table that generates a buttons dynamically and I would like to change the colour and the text when I execute a function onclick. The text is modified correctly but when execute the function all buttons change the colour at the same time.

I use bootstrap 3 and the structure on my server is:

  • index.php -> I load css, scripts, jquery and my functions.
  • ajax/readRecords.php --> I generate the mysql table
  • js/script.js --> my function onclik
  • js/jquery.js --> the jquery

The php code:

    while($row = mysqli_fetch_assoc($result))
    {
        $status = $row['register_status'];
        if ($status == "Active") {
            $register_status = '<button class="btn btn-success btn_status btn-block" data-status="Active">Active</button>';
        }
        else {
            $register_status = '<button class="btn btn-warning btn_status btn-block" data-status="Inactive">Inactive</button>';
        }
        $data .= '<tr>
                        <td width="1%"><mark>#'.$row['id'].'</mark></td>
                        <td>'.$row['first_name'].'</td>
                        <td>'.$row['last_name'].'</td>
                        <td>'.$row['email'].'</td>
                        <td width="1%">'.$register_status.'</td>
                        <td width="1%">

and this is the jquery function:

jQuery(document).ready(function(){
  $('body').click('.btn_status', function(e){
  var button = jQuery(e.target);
  if(button.data('status') == 'Active'){
          button.data('status', 'Inactive');
          button.html('Inactive');
        button.removeClass("btn-success").addClass("btn-warning");
        }else if(button.data('status') == 'Inactive'){
          button.data('status', 'Active');
          button.html('Active');
          button.removeClass("btn-warning").addClass("btn-success");
        }
  });
})

I sense that the value of the class is lost but can't know what's the solution. thanks!

Barmar
  • 741,623
  • 53
  • 500
  • 612
Guif If
  • 535
  • 2
  • 7
  • 18
  • You're using the wrong signature for click. Should be either `$(".btn_status").click(function...` if the buttons are create during render or `$(document).on("click", ".btn_status", function...` if the buttons are added later (dynamically) – freedomn-m Jul 01 '19 at 20:54
  • Possible duplicate of [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – freedomn-m Jul 01 '19 at 20:55
  • the buttons are generate at the same time that I generate the table. – Guif If Jul 01 '19 at 21:00
  • You're generating the HTML before the JS runs, not using AJAX, right? Then it's not dynamic as far as JavaScript is concerned. The fact that it came from a dynamic query in PHP is invisible to the browser. – Barmar Jul 01 '19 at 21:40
  • yes. first generate the table and later have the scripts (onclik function) – Guif If Jul 01 '19 at 21:43

0 Answers0