Как получить идентификатор строки onClick в jQuery / JavaScript? - PullRequest
1 голос
/ 05 августа 2020

У меня есть таблица, заполненная динамическими c данными. в последнем столбце есть кнопка, при нажатии которой я хотел бы передать идентификатор строки функции JS. Мне нужен идентификатор, потому что я выполняю запрос POST Ajax, и в случае успеха я хочу взять данные ответа и обновить выбранную строку новыми данными.

Это то, что я сделал бы, чтобы вставить новую строку :

var rowNode = myTable.row.add([1,2,3,4,5,6,7,8]).draw();

но что я могу сделать, чтобы получить идентификатор строки и обновить его данными ответа?

EDIT. Дата:

<table id="myTable" class="display compact" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>Name</th>
                <th>Reg</th>  
                <th>Edit</th>                   
            </tr>
        </thead>
        <tbody>
            <?php foreach (get_all_customers_list() as $user) { ?>
                    <tr>
                        <td>
                            <b> <?php echo $user["recipient_name"]; ?></b>
                        </td>
                        <td>
                            <?php echo $user["registration_date"]; ?>
                        </td>                       
                        <td>
                            <button type="button" id="button_edit" onclick='edit_customer_request(<?php echo json_encode($user); ?>)' value="<?php echo $user; ?>" name="edit_customer">Editt</button>                             
                        </td>
                    </tr>
            <?php }?>
        </tbody>
 </table>

1 Ответ

0 голосов
/ 05 августа 2020

Так как вы хотите получить только row id кнопки редактирования строки clicked. Вы можете просто использовать функцию table.row и передать фактическое tr нажатой кнопки.

Demo (Показывает actual id (1, 2), который сохраняется как имя)

var table = $('#myTable').DataTable({})

//edit customer here
function edit_customer_request(_this) {
  //Getting the actual table ID
  var row = $(_this).parents('tr')[0];
  //Data table row id
  console.log(table.row(row).data()[0]);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/js/jquery.dataTables.min.js" integrity="sha512-BkpSL20WETFylMrcirBahHfSnY++H2O1W+UnEEO4yNIl+jI2+zowyoGJpbtk6bx97fBXf++WJHSSK2MV4ghPcg==" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/css/jquery.dataTables.min.css" integrity="sha512-1k7mWiTNoyx2XtmI96o+hdjP8nn0f3Z2N4oF/9ZZRgijyV4omsKOXEnqL1gKQNPy2MTSP9rIEWGcH/CInulptA==" crossorigin="anonymous" />
<table id="myTable" class="display compact" cellspacing="0" width="100%">
  <thead>
    <tr>
      <th>Name</th>
      <th>Reg</th>
      <th>Edit</th>
    </tr>
  </thead>

  <tbody>
    <tr>
      <td>1</td>
      <td>Tiger Blah</td>
      <td><button type="button" class="button_edit" onclick='edit_customer_request(this, 1)' value="1" name="edit_customer">Edit</button></td>
    </tr>tr>
    <tr>

      <td>2</td>
      <td>Blah Nixon</td>
      <td><button type="button" class="button_edit" onclick='edit_customer_request(this ,2)' value="2" name="edit_customer">Edit</button></td>
    </tr>
  </tbody>
</table>

Демо (Отображение фактического индекса таблицы - начало индекса от 0 до в зависимости от количества строк)

var table = $('#myTable').DataTable({})

//edit customer here
function edit_customer_request(_this) {
  //get the closest of clicked edit button
  var tr = $(_this).closest("tr");
  //get the index of row
  var rowindex = tr.index();
  //Index of row
  console.log(rowindex)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/js/jquery.dataTables.min.js" integrity="sha512-BkpSL20WETFylMrcirBahHfSnY++H2O1W+UnEEO4yNIl+jI2+zowyoGJpbtk6bx97fBXf++WJHSSK2MV4ghPcg==" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/css/jquery.dataTables.min.css" integrity="sha512-1k7mWiTNoyx2XtmI96o+hdjP8nn0f3Z2N4oF/9ZZRgijyV4omsKOXEnqL1gKQNPy2MTSP9rIEWGcH/CInulptA==" crossorigin="anonymous" />
<table id="myTable" class="display compact" cellspacing="0" width="100%">
  <thead>
    <tr>
      <th>Name</th>
      <th>Reg</th>
      <th>Edit</th>
    </tr>
  </thead>

  <tbody>
    <tr>
      <td>1</td>
      <td>Tiger Blah</td>
      <td><button type="button" class="button_edit" onclick='edit_customer_request(this, 1)' value="1" name="edit_customer">Edit</button></td>
    </tr>tr>
    <tr>

      <td>2</td>
      <td>Blah Nixon</td>
      <td><button type="button" class="button_edit" onclick='edit_customer_request(this ,2)' value="2" name="edit_customer">Edit</button></td>
    </tr>
  </tbody>
</table>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...