javascript - How to select Just 1 Row from a Table using Jquery -
i have created table display multiple records..i want add update functionality using ajax..
i have written following code, when click on row make rows editable..i want edit specific row in clicked.
kindly guide me how achieve this.
<button type="button" class="updateuser btn btn-primary btn-xs" data-userid="<?php echo $id; ?>"> <span class="glyphicon glyphicon-pencil"></span> </button> $(document).on("click", ".updateuser", function(){ $('tr td:nth-child(2)').each(function () { var html = $(this).html(); var input = $('<input type="text" />'); input.val(html); $(this).html(input); }); });
edit - html code
<table class="table table-hover"> <thead> <tr> <th>#</th> <th>username</th> <th>password</th> <th>role</th> <th>edit</th> <th>delete</th> </tr> </thead> <tbody> <tr> <td>"php dynamic id "</td> <td>"php dynamic username "</td> <td>"php dynamic password "</td> <td>"php dynamic role "</td> <td> <button type="button" class="updateuser btn btn-primary btn-xs" data-userid="<?php echo $id; ?>"> <span class="glyphicon glyphicon-pencil"></span> </button> </td> <td> <button class="deleteuser btn btn-danger btn-xs" type="button" data-userid="<?php echo $id; ?>"> <span class="glyphicon glyphicon-remove"></span> </button> </td> </tr> </tbody> </table>
it's selecting every row because that's $('tr td:nth-child(2)')
telling do.
i'm not huge fan of binding delegated events on 'document' unnecessarily; makes handlers run way check if clicked on relevant.
it's better bind event closer relevant tags -- either on edit button (and traverse upwards find desired table row) or on table (as shown here, in case need add rows programmatically , don't want have rebind individual events new rows.)
(updated answer you've edited question show want catch clicks on button rather on entire row)
$('table').on('click', '.updaterow', function() { var mytd = $(this).closest('tr').find('td:eq(1)'); // gets second table cell in clicked row // whatever mytd, such as: $('td').removeclass('selected'); // remove previous selections mytd.addclass('selected'); });
table {border-collapse:collapse} td {border:1px solid} .selected {background-color: red} .updaterow {color: #00f; text-decoration:underline}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr><td class="updaterow">edit:</td><td>a </td><td>b </td><td>c </td><td>easy as</td></tr> <tr><td class="updaterow">edit:</td><td>one </td><td>two</td><td>three </td><td>or simple as</td></tr> <tr><td class="updaterow">edit:</td><td>do </td><td>re </td><td>me </td><td>baby</td></tr> <tr><td class="updaterow">edit:</td><td>that's</td><td>how</td><td>simple</td><td>love can be</td></tr> </table>
Comments
Post a Comment