How to get the row id onClick in jQuery/JavaScript? - javascript

I have a table populated with dynamic data. the last column has a button which when I click I would like to pass the row id to the JS function.
I need the id because I am doing a POST Ajax request and on success I want to take the response data and update the selected row with new data.
This is what I would do to insert a new row:
var rowNode = myTable.row.add([1,2,3,4,5,6,7,8]).draw();
but what can I do to get the row ID and update it with the response data?
EDIT. Datatable:
<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>

Since you are only wanted to get the row id of the clicked row edit button. You can simply use table.row function and pass the actual tr of the clicked button.
Demo (Showing the actual id (1, 2) which is stored as name)
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>
Demo (Showing the actual index of table - Index start from 0 to depending on how many rows you have)
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>

this is my simple answer:
var table = $('#table-values');
$('#table-values').on( 'click', 'tr', function(){
var id = this.id;
alert( 'Clicked row id '+id );
});
Easy. :)

Related

I need to copy selected row from one table to another html table using JQuery or Javascript

I have data in source table and i want to copy and append row to destination table on button click of specific row. There is an h1 where I want to display column total of price column of destination table. Also I need button on destination table from which I can remove the selected row from that table.
<table id="source_table" >
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
<th>Action Copy</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td >Product 1</td>
<td >$10</td>
<td>
<button type="button" class="copy-row" >+</button>
</td>
</tr>
<tr>
<td>2</td>
<td >Product 2</td>
<td >$20</td>
<td>
<button type="button" class="copy-row" >+</button>
</td>
</tr>
<tr>
<td>3</td>
<td >Product 3</td>
<td >$30</td>
<td>
<button type="button" class="copy-row" >+</button>
</td>
</tr>
</tbody>
</table>
<table id="dest_table" >
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
<th>Action Delete</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<div> Total Price <h1> <!-- I want to show price column(dest_table) total here -> </h1> </div>
Consider the following example.
$(function() {
function calcTotal(t) {
var rows = $("tbody tr", t);
var total = 0.00;
var val;
rows.each(function(i, r) {
val = $("td:eq(2)", r).text().substr(1);
total += parseFloat(val);
});
$(".total").html("$" + total);
}
$(".copy-row").click(function(e) {
var src = $(this).closest("tr");
var dst = $("#dest_table tbody");
src.clone().appendTo(dst);
$("#dest_table tbody tr:last td:eq(3) button").toggleClass("copy-row del-row").html("X");
calcTotal($("#dest_table"));
});
$("#dest_table tbody").on("click", ".del-row", function(e) {
if (confirm("Are you sure you want to remove this row?")) {
$(this).closest("tr").remove();
}
calcTotal($("#dest_table"));
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="source_table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
<th>Action Copy</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Product 1</td>
<td>$10</td>
<td>
<button type="button" class="copy-row">+</button>
</td>
</tr>
<tr>
<td>2</td>
<td>Product 2</td>
<td>$20</td>
<td>
<button type="button" class="copy-row">+</button>
</td>
</tr>
<tr>
<td>3</td>
<td>Product 3</td>
<td>$30</td>
<td>
<button type="button" class="copy-row">+</button>
</td>
</tr>
</tbody>
</table>
<table id="dest_table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
<th>Action Delete</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<div class="total"> Total Price
<h1></h1>
</div>
This makes use of a lot of elements, yet at it's core, it does clone the row, and appends the clone to the destination.
Do you want something like this:
$(document).ready(function(){
$(".copy-row").click(function(){
var currentRow=$(this).closest("tr");
var col1=currentRow.find("td:eq(0)").text(); // get current row 1st TD value
var col2=currentRow.find("td:eq(1)").text(); // get current row 2nd TD
var col3=currentRow.find("td:eq(2)").text(); // get current row 3rd TD
var col4=currentRow.find("td:eq(3)").text(); // get current row 4th TD
var markup = "<tr><td>" + col1 + "</td><td>" + col2 + "</td><td>" + col3 + "</td><td>" + col4 + "</td></tr>";
$("#dest_table tbody").append(markup);
// sum of price
var sum = 0;
$('#dest_table tbody tr').each(function() {
var price = $(this).find('td:eq(2)').text();
price = price.replace('$', '');
sum += parseInt(price);
});
$('#total').text('$' + sum);
});
});
But I highly recommend you use some framework like React, Vue or Svelte. Your life will be easier.

How to save table with contenteditable column into local storage

I'm trying to save the content of column 3, with id name = 'edit' in the table, locally. Here is the code:
// Button to save edit
function saveEdits() {
var table, tr, editElem, userVersion, i, j;
table = document.getElementById("mytable");
tr = table.getElementByClassName("output");
editElems = {
for (i=0; i< tr.length; i++){
//get the editable element
userVersion[i] : tr[i].getElementsById("edit").innerHTML;
}
}
localStorage.setItem('userEdits', JSON.stringify(editElems));
}
// place in the body to reload the changes
function checkEdits() {
var userEdits = localStorage.getItem('userEdits');
if (userEdits) {
userEdits = JSON.parse(userEdits);
for ( var elementId in userEdits ) {
document.getElementById(elementId).innerHTML = userEdits[elementId];
}
}
}
I am following tutorial in https://www.developerdrive.com/allowing-users-to-edit-text-content-with-html5/, but I want to apply it to the table, however, it doesn't work.
Here is my html code
<!doctype html>
<html>
<head>
<title>BOOK LIST</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css">
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>
<script src=./javascript.js></script>
</head>
<body onload="checkEdits()">
<div class="header">
<h1>BOOK</h1>
</div>
<div class="tbody">
<table id="mytable" align="center" class="table table-striped table-bordered" cellspacing="0">
<thead>
<tr>
<th width="5%">#</th>
<th width="20%">BOOK NAME</th>
<th width="50%">AUTHOR</th>
<th width="25%">DESCRIPTION</th>
</tr>
</thead>
<tbody>
<tr class='output'>
<td>1</td>
<td>BOOK 1</td>
<td>John</td>
<td id='edit' contenteditable='true'>No Description</td>
</tr>
<tr class='output'>
<td>2</td>
<td>BOOK 2</td>
<td>Sara</td>
<td id='edit' contenteditable='true'>No Description</td>
</tr>
<tr class='output'>
<td>3</td>
<td>BOOK 3</td>
<td>Mary</td>
<td id='edit' contenteditable='true'>No Description</td>
</tr>
<tr class='output'>
<td>4</td>
<td>BOOK 4</td>
<td>Bob</td>
<td id='edit' contenteditable='true'>No Description</td>
<!---- TABLE FILTER AND SORT FUNCTION ---->
<script>
$(document).ready(function() {
$('#mytable').DataTable( {
"pagingType": "full_numbers"
});
});
</script>
</tbody>
</table>
<!--------------------- EDIT FILE ----------------------------------------------->
<input id='saveComment' type='button' value='Save' onclick='saveEdits()'>
<!------------------------------------------------------------------------------->
</div>
</body>
</html>
There are some bugs in the code:
tr = table.getElementByClassName("output"); // it is getElementsByClassName
secondly, I don't know if this style of declaring a JSON is valid or not but since it didn't worked, I changed it and saved the values first to an array and then converted it to a JSON String.
Another thing is that the way you are trying to store key value pairs in JSON you won't be able to get a selector in a JSON String and hence you won't be able to update the values correctly. So, i have used an associative array where it's keys are the row number in which the edit was performed and the value holds the new content of that column. So, while updating you just have to select the desired column from a row in which the values should be updated.
This is working fine:
// Button to save edit
var TR;
function saveEdits() {
var table, tr, editElem, userVersion = [], i, j;
table = document.getElementById("mytable");
tr = table.getElementsByClassName("output"); //element
TR = tr;
console.log(tr);
for (i=0; i< tr.length; i++){
// This will set a key value pair where key as row number and value as the inner HTML
// This key will further help us updating the values from localhost
userVersion[tr[i].sectionRowIndex] = tr[i].getElementsByTagName("td")[3].innerHTML;
}
console.log(userVersion);
localStorage.setItem('userEdits', JSON.stringify(userVersion));
}
// place in the body to reload the changes
function checkEdits() {
try{
var userEdits = localStorage.getItem('userEdits');
//console.log(JSON.parse(userEdits));
if (userEdits) {
userEdits = JSON.parse(userEdits);
table = document.getElementById("mytable");
tr = table.getElementsByClassName("output"); //element
for ( var elementId in userEdits ) {
tr[elementId].getElementsByTagName("td")[3].innerHTML = userEdits[elementId];
}
}
}catch{
//console.log("Hello");
}
}
<!doctype html>
<html>
<head>
<title>BOOK LIST</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css">
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>
</head>
<body onload="checkEdits()">
<div class="header">
<h1>BOOK</h1>
</div>
<div class="tbody">
<table id="mytable" align="center" class="table table-striped table-bordered" cellspacing="0">
<thead>
<tr>
<th width="5%">#</th>
<th width="20%">BOOK NAME</th>
<th width="50%">AUTHOR</th>
<th width="25%">DESCRIPTION</th>
</tr>
</thead>
<tbody>
<tr class='output'>
<td>1</td>
<td>BOOK 1</td>
<td>John</td>
<td id='edit' contenteditable='true'>No Description</td>
</tr>
<tr class='output'>
<td>2</td>
<td>BOOK 2</td>
<td>Sara</td>
<td id='edit' contenteditable='true'>No Description</td>
</tr>
<tr class='output'>
<td>3</td>
<td>BOOK 3</td>
<td>Mary</td>
<td id='edit' contenteditable='true'>No Description</td>
</tr>
<tr class='output'>
<td>4</td>
<td>BOOK 4</td>
<td>Bob</td>
<td id='edit' contenteditable='true'>No Description</td>
<!---- TABLE FILTER AND SORT FUNCTION ---->
<script>
$(document).ready(function() {
$('#mytable').DataTable( {
"pagingType": "full_numbers"
});
});
</script>
</tbody>
</table>
<!--------------------- EDIT FILE ----------------------------------------------->
<input id='saveComment' type='button' value='Save' onclick='saveEdits()'>
<!------------------------------------------------------------------------------->
</div>
</body>
</html>

How to add rows in HTML Table using Jquery?

I want to add rows dynamically at runtime using Jquery. At beginning table don't have any records. When user click the ADD Button it has to add the rows.
When user click ADD Button the operator dropdown list box value and Filter values should add in that table row.
Here what I tried
Jquery CODE
$("#btnAdd").click(function () {
// $("#queryTable tr:last").after("<tr>...</tr><tr>...</tr>");
$('#queryTable > tbody:last-child').append('<tr>Record1</tr><tr>Record2</tr>');
});
I tried both lines. But it doesn't make any sense.
Thanks
HTML Code
<table class="table table-hover " id="queryTable">
<thead>
<tr>
<th>Field Name</th>
<th>Values</th>
</tr>
</thead>
<tbody>
<tr>
<td>Mark</td> //Please ignore these two records. At beginning the table will be empty
<td>Otto</td>
</tr>
<tr>
<td>Jacob</td>
<td>Thornton</td>
</tr>
</tbody>
</table>
The correct jQuery code to add HTML elements is:
$('#queryTable tbody').append('<tr><td>Record1</td><td>Record2</td></tr>');
Your input string HTML is incorrect. As of now you have no TD element thus content is not displayed. However its appended and exists in DOM
'<tr><td>Record1</td><td>Record2</td></tr>
instead of
'<tr>Record1</tr><tr>Record2</tr>'
$('#queryTable > tbody:last-child').append('<tr><td>Record1</td><td>Record2</td></tr>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-hover" id="queryTable">
<thead>
<tr>
<th>Field Name</th>
<th>Values</th>
</tr>
</thead>
<tbody>
<tr>
<td>Mark</td>
<td>Otto</td>
</tr>
<tr>
<td>Jacob</td>
<td>Thornton</td>
</tr>
</tbody>
</table>
<!DOCTYPE html>
<html>
<head>
<title>Add Rows Dynamically</title>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".add").click(function(){
var name = $("#name").val();
var lastname = $("#lastname").val();
var markup = "<tr><td>" + name + "</td><td>" + lastname + "</td></tr>";
$("table tbody").append(markup);
});
});
</script>
</head>
<body>
<input type="text" id="name" placeholder="Name">
<input type="text" id="lastname" placeholder="Last Name">
<input type="button" class="add" value="Add">
<table style="border: 1px solid black;">
<thead>
<tr>
<th>Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>
It may help you.

Get values of table row and print them in another div

I am retrieving values from database and print them in table. Now I want to get values to another div and place them in form.
I am using twitter bootstrap.
First I get values from database and print them in table
<div class="col-xs-10">
<table id="example" class="table table-bordered table-striped">
<thead>
<tr class="bg-red">
<th>Id</th>
<th>Name</th>
<th>Quality</th>
<th>Dimensions</th>
<th>COlor</th>
<th>Add</th>
</tr>
</thead>
<tbody>
<?php
while($r=$q->fetch()){ ?>
<tr>
<td><?='Nb'. $r['Id']?> </td>
<td> <?=$r['MatVrstaNaziv']?> </td>
<td><?=$r['Quality']?></td>
<td><?=$r['Width'] . ' X '. $r['Height']?></td>
<td><?=$r['COlor']?></td>
<td> <button class="addValues" value="<?='Nb'. $r['Id']?> "> Add</button></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<div class="col-xs-2">
<div id="selection">
</div>
</div>
I have added button Add to add that row in another div. For that I am using script
<script>
$(function () {
$(".addValues").click(function () {
var $this = $(this),
myCol = $this.closest("td"),
myRow = myCol.closest("tr"),
targetArea = $("#selection");
targetArea.append(myRow.children().not(myCol).text() + "<br />");
});
});
</script>
This script does not work it does not print values in specified div. I only want to print id number in another div.
Could someone give me advice what is wrong?
When you add . before addValues in selector $(".addValues") its work, see example bellow with static data.
If it still not working that mean you have problem in your PHP code, check if the query return valide result and check name of attributes like 'COlor' for example.
$(".addValues").click(function () {
$('#selection').show();
var $this = $(this),
myCol = $this.closest("td"),
myRow = myCol.closest("tr"),
targetArea = $("#selection");
var rowId = $("td.data-id", myRow).text();
var qte_input = (' <input type="text" placeholder="Qte" size="5"/>');
targetArea.prepend(rowId + qte_input +"<br />");
});
table, th, td {
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-xs-10">
<table id="example" class="table table-bordered table-striped">
<thead>
<tr class="bg-red">
<th>Id</th>
<th>Name</th>
<th>Quality</th>
<th>Dimensions</th>
<th>COlor</th>
<th>Add</th>
</tr>
</thead>
<tbody>
<tr>
<td class='data-id'> 1</td>
<td> bb</td>
<td> ccc</td>
<td> dd X '. dd</td>
<td> ee</td>
<td> <button class="addValues" value="fff"> Add</button></td>
</tr>
<tr>
<td class='data-id'>2</td>
<td> YYY</td>
<td> ccc</td>
<td> dd X '. dd</td>
<td> ee</td>
<td> <button class="addValues" value="fff"> Add</button></td>
</tr>
<tr>
<td class='data-id'>3</td>
<td> XXX</td>
<td> ccc</td>
<td> dd X '. dd</td>
<td> ee</td>
<td> <button class="addValues" value="fff"> Add</button></td>
</tr>
</tbody>
</table>
</div>
<div class="col-xs-2">
<div id="selection" style="display: none">
</br>
<button class="submitValues">Submit</button>
</div>
</div>

How get grand parent text in a table with jquery

I have some problems in accessing the text about a grand parent td in table.
When I click on delete, I would like that my function accesses the grand parent text : "fabien" but all I received is undefined.
this is my HTML:
<table class="table table-striped">
<thead>
<tr>
<td>Name</td>
<td>Delete</td>
</tr>
</thead>
<tbody id="tabSelectUser">
<tr>
<td> fabien </td>
<td><a onclick="javascript:aButtonPressed();"> delete</a></td>
</tr> </tbody>
</table>
and this is my function:
<script type="text/javascript">
function aButtonPressed(){
var prevCell = $(this).parent().prev().text();
console.log(prevCell);
</script>
Use Jquery to bind the click event, then your $(this) will work.
<table class="table table-striped">
<thead>
<tr>
<td>Name</td>
<td>Delete</td>
</tr>
</thead>
<tbody id="tabSelectUser">
<tr>
<td> fabien </td>
<td> delete</td>
</tr> </tbody>
</table>
Javascript:
$(function() {
$('.deleteBtn').click(aButtonPressed);
});
function aButtonPressed(){
var prevCell = $(this).parent().prev().text();
console.log(prevCell);
}
$(".childclass").parents("eq(numberofnthparent)").text();

Categories