简体   繁体   English

Jquery从表的第二行选择data-id

[英]Jquery select data-id from second row on table

I've been trying to make a table with a list of users for a school project. 我一直在努力制作一个包含学校项目用户列表的表格。 I'm doing this with jquery, php and mysql. 我用jquery,php和mysql做这个。

I'm retrieving all data from the mysql database and printing it out in a table. 我正在从mysql数据库中检索所有数据并将其打印在表格中。 now i'm trying to add an update button to i can easily update data for each specific row. 现在我正在尝试添加更新按钮,我可以轻松更新每个特定行的数据。

This however is not working as expected. 然而,这并没有按预期工作。 It only selects the data from the same row. 它只选择同一行的数据。 While the data-id value is different. 虽然data-id值不同。 Could anyone tell me why this is happening? 谁能告诉我为什么会这样? I'll leave my code below for clearance 我将保留下面的代码以便清除

JS: JS:

$(document).ready(function () {
   $(document).on('click', '#update-btn', function () {
       var id =$("[id='update-btn']").attr('data-id');
       var username = $('#username').val();
       var dob = $('#dob').val();
       var address = $('#address').val();

       $.ajax({
          url: 'ajax/update.php',
          method: 'POST',
          data: {
              ID: id,
              username: username,
              dob: dob,
              address: address
          },
          success: function (data) {
              if (data){
                  console.log(data);
                  swal({
                      title: 'Update successful',
                      icon: 'success',
                      text: 'User with ID ' + id + ' updated.'
                  });
                  setTimeout(function () {
                      window.location = 'medewerkers.php';
                  }, 5000)

              }
              else if (data === "update_failed"){

              }
          }
       });
   });
});

PHP: PHP:

public static function loadMedewerkers(){
$mysql = Database::DBCon()->prepare('

    SELECT * FROM medewerkers

');
$mysql->execute();

while ($fetch = $mysql->fetch(PDO::FETCH_ASSOC))
{

    $html = '<tr>
                <td><input type="text" value="'. $fetch['username'] .'" id="username"></td>
                <td><input type="text" value="'. $fetch['dob'] .'" id="dob"></td>
                <td><input type="text" value="'. $fetch['address'] .'" id="address"</td>
                <td><button type="button" class="btn btn-danger" id="delete-btn" data-id="'. $fetch['ID'] .'">Delete</button>
                    <button type="button" class="btn btn-warning" id="update-btn" data-id="'. $fetch['ID'] .'">Update</button></td>
             </tr>';
    echo $html;
}

} }

The problem is because your loop is causing multiple elements to have the same id , when id attributes must be unique within the DOM. 问题是,因为你的循环是造成多个元素具有相同的id ,当id属性必须是DOM中是唯一的。 To fix this use common classes on the elements within the loop, then DOM traversal to find them when the button is clicked. 要修复此问题,请在循环内的元素上使用公共类,然后DOM遍历以在单击button时找到它们。

public static function loadMedewerkers()
{
  $mysql = Database::DBCon()->prepare('SELECT * FROM medewerkers');
  $mysql->execute();
  while ($fetch = $mysql->fetch(PDO::FETCH_ASSOC))
  {
    $html = '<tr>
      <td><input type="text" value="'. $fetch['username'] .'" class="username"></td>
      <td><input type="text" value="'. $fetch['dob'] .'" class="dob"></td>
      <td><input type="text" value="'. $fetch['address'] .'" class="address"</td>
      <td>
        <button type="button" class="btn btn-danger delete-btn" data-id="'. $fetch['ID'] .'">Delete</button>
        <button type="button" class="btn btn-warning update-btn" data-id="'. $fetch['ID'] .'">Update</button></td>
    </tr>';
    echo $html;
  }
}
$(document).ready(function() {
  $(document).on('click', '.update-btn', function() {
    var $row = $(this).closest('tr');
    var id = $(this).data('id');
    var username = $row.find('.username').val();
    var dob = $row.find('.dob').val();
    var address = $row.find('.address').val();

    // ajax request here...
  });
});

Note the use of data() to retrieve the data attribute. 注意使用data()来检索data属性。 Also note that you could put the data-id attribute itself on the tr instead of each button to DRY up the HTML slightly. 另请注意,您可以将data-id属性本身放在tr而不是每个button上稍微干掉HTML。

You are using ID in your buttons when returning ID is unique for each object in the screen try using class something like this: 您在按钮中使用ID时返回ID对于屏幕中的每个对象都是唯一的尝试使用类似这样的类:

$(document).ready(function () {
   $(document).on('click', '.update-btn', function () {
       var id =$(this).data('id');
       var username = $(this).closest('tr').find('.username').val();
       var dob = $(this).closest('tr').find('.dob').val();
       var address = $(this).closest('tr').find('.address').val();

       $.ajax({
          url: 'ajax/update.php',
          method: 'POST',
          data: {
              ID: id,
              username: username,
              dob: dob,
              address: address
          },
          success: function (data) {
              if (data){
                  console.log(data);
                  swal({
                      title: 'Update successful',
                      icon: 'success',
                      text: 'User with ID ' + id + ' updated.'
                  });
                  setTimeout(function () {
                      window.location = 'medewerkers.php';
                  }, 5000)

              }
              else if (data === "update_failed"){

              }
          }
       });
   });
});



public static function loadMedewerkers(){
$mysql = Database::DBCon()->prepare('

    SELECT * FROM medewerkers

');
$mysql->execute();

while ($fetch = $mysql->fetch(PDO::FETCH_ASSOC))
{

    $html = '<tr>
                <td><input type="text" value="'. $fetch['username'] .'" class="username"></td>
                <td><input type="text" value="'. $fetch['dob'] .'" class="dob"></td>
                <td><input type="text" value="'. $fetch['address'] .'" class="address"</td>
                <td><button type="button" class="btn btn-danger delete-btn" data-id="'. $fetch['ID'] .'">Delete</button>
                    <button type="button" class="btn btn-warning update-btn" data-id="'. $fetch['ID'] .'">Update</button></td>
             </tr>';
    echo $html;
}
}

same goes for your delete button 删除按钮也一样

and use .data() instead of attr() 并使用.data()而不是attr()

Also, in other columns for getting the username, dob and address you have to use class instead of id . 此外,在获取用户名,dob和地址的其他列中,您必须使用class而不是id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM