searching specific html table column - javascript

hello can someone help me with this. the search is working
but how can i exclude the last column to be searched?
i have three columns, first name, lastname and email.
what i want is to search using the two columns only. and exclude the column email when searching. thank you
this is my javascript code
<script type="text/javascript">
function doSearch() {
var searchText = document.getElementById('searchTerm').value;
var targetTable = document.getElementById('report');
var targetTableColCount;
//Loop through table rows
for (var rowIndex = 0; rowIndex < targetTable.rows.length; rowIndex++ ) {
var rowData = '';
//Get column count from header row
if (rowIndex == 0) {
targetTableColCount = targetTable.rows.item(rowIndex).cells.length;
continue; //do not execute further code for header row.
}
//Process data rows. (rowIndex >= 1)
for (var colIndex = 0; colIndex < targetTableColCount; colIndex++) {
var cellText = '';
if (navigator.appName == 'Microsoft Internet Explorer')
cellText = targetTable.rows.item(rowIndex).cells.item(colIndex).innerText;
else
cellText = targetTable.rows.item(rowIndex).cells.item(colIndex).textContent;
rowData += cellText;
}
// Make search case insensitive.
rowData = rowData.toLowerCase();
searchText = searchText.toLowerCase();
//If search term is not found in row data
//then hide the row, else show
if (rowData.indexOf(searchText) == -1)
targetTable.rows.item(rowIndex).style.display = 'none';
else
targetTable.rows.item(rowIndex).style.display = 'table-row';
}
}
</script>
and this is my html code
<input id="searchTerm" class="form-control" placeholder="Enter text" onkeyup="doSearch()">
<table id="report" class="table">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>Doe</td>
<td>john#example.com</td>
</tr>
<tr>
<td>Mary</td>
<td>Moe</td>
<td>mary#example.com</td>
</tr>
<tr>
<td>July</td>
<td>Dooley</td>
<td>july#example.com</td>
</tr>
</tbody>
</table>
i have another question. i added an expandable row on my html table
and now the search doesnt give the desired output. example when i search for a value that are not on the html table it just remove the first row and show the rest of the row. which is not the correct output.
<table id="report" class="table">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>Doe</td>
<td>john#example.com</td>
<td>
<div class="arrow"><a id="menu-toggle" href="#" ><i class="glyphicon glyphicon-plus-sign"></i></a></div>
</td>
</tr>
<tr><td colspan="4">
<button type="button" class="btnview btn btn-xs btn-warning" >
<span class="glyphicon glyphicon-remove-circle" aria-hidden="true"></span>View
</button>
</td>
</tr>
<tr>
<td>Mary</td>
<td>Moe</td>
<td>mary#example.com</td>
<td>
<div class="arrow"><a id="menu-toggle" href="#" ><i class="glyphicon glyphicon-plus-sign"></i></a></div>
</td>
</tr>
<tr><td colspan="4">
<button type="button" class="btnview btn btn-xs btn-warning" >
<span class="glyphicon glyphicon-remove-circle" aria-hidden="true"></span>View
</button>
</td>
</tr>
<tr>
<td>July</td>
<td>Dooley</td>
<td>july#example.com</td>
<td>
<div class="arrow"><a id="menu-toggle" href="#" ><i class="glyphicon glyphicon-plus-sign"></i></a></div>
</td>
</tr>
<tr><td colspan="4">
<button type="button" class="btnview btn btn-xs btn-warning" >
<span class="glyphicon glyphicon-remove-circle" aria-hidden="true"></span>View
</button>
</td>
</tr>
</tbody>
</table>
sir roman after integrating you're code to mine. the search is now working as expected. but when the searchterm input is empty and i press backspace on it. it became like this
https://jsfiddle.net/t6xg97uo/

I believe this should answer your issue. I am simply adjusting how many columns you are searching:
for (var colIndex = 0; colIndex < (targetTableColCount-1); colIndex++) {
Here is an example:
http://codepen.io/anon/pen/PNWNmL
Update
Ok, I am not sure this is the right fix for what you are looking for, but I just commented out the code that is causing that button to be revealed when backspacing. Here is what I did:
<tbody>
<tr>
<td>John</td>
<td>Doe</td>
<td>john#example.com</td>
<td>
<div class="arrow"><a id="menu-toggle" href="#" ><i class="glyphicon glyphicon-plus-sign"></i></a></div>
</td>
</tr>
<tr>
<!-- <td colspan="4">
<button type="button" class="btnview btn btn-xs btn-warning" >
<span class="glyphicon glyphicon-remove-circle" aria-hidden="true"></span>View
</button>
</td> -->
</tr>
<tr>
<td>Mary</td>
<td>Moe</td>
<td>mary#example.com</td>
<td>
<div class="arrow"><a id="menu-toggle" href="#" ><i class="glyphicon glyphicon-plus-sign"></i></a></div>
</td>
</tr>
<tr>
<!-- <td colspan="4">
<button type="button" class="btnview btn btn-xs btn-warning" >
<span class="glyphicon glyphicon-remove-circle" aria-hidden="true"></span>View
</button>
</td> -->
</tr>
<tr>
<td>July</td>
<td>Dooley</td>
<td>july#example.com</td>
<td>
<div class="arrow"><a id="menu-toggle" href="#" ><i class="glyphicon glyphicon-plus-sign"></i></a></div>
</td>
</tr>
<tr>
<!-- <td colspan="4">
<button type="button" class="btnview btn btn-xs btn-warning" >
<span class="glyphicon glyphicon-remove-circle" aria-hidden="true"></span>View
</button>
</td> -->
</tr>
</tbody>
And here is a jsfiddle:
https://jsfiddle.net/t6xg97uo/1/

Solution including you additional requirement(with an expandable row within a table):
- replace your nested for loop(through row columns) as shown below:
(you should also skip rows which have only one cell(td) from processing)
...
var rowCells = targetTable.rows.item(rowIndex).cells, cellsLen = rowCells.length;
if (cellsLen > 1) {
for (var colIndex = 0; colIndex < 2; colIndex++) {
var cellText = '';
if (targetTable.rows.item(rowIndex).cells.item(colIndex)) {
cellText = rowCells.item(colIndex)[(navigator.appName == 'Microsoft Internet Explorer')? "innerText" : "textContent"];
}
rowData += cellText;
}
}
// Make search case insensitive.
rowData = rowData.toLowerCase().trim();
searchText = searchText.toLowerCase();
//If search term is not found in row data
//then hide the row, else show
if (cellsLen > 1) {
if (searchText && rowData.indexOf(searchText) === -1) {
targetTable.rows.item(rowIndex).style.display = 'none';
} else {
targetTable.rows.item(rowIndex).style.display = 'table-row';
}
}
...

Related

Enable button if all rows below have been deleted

I have created with JQuery a table where I can add a certain text by pressing a button.
As you can see Product 2 and Product 3 can only be added once. Product 4 can be added several times. All text that is inserted can also be deleted by pressing the x-button.
$(".btn.btn-primary.btn-sm").on("click", this.ourClickDispatcher.bind(this))
$("#tableProd").on("click", ".btn.btn-danger.btn-sm.deleteMe", this.deleteRow.bind(this))
function deleteRow(e) {
let deleteBtn = $(e.target).closest(".deleteMe");
deleteBtn.closest('tr').remove()
}
function ourClickDispatcher(e) {
let targetButton = $(e.target).closest(".btn.btn-primary.btn-sm")
let targetButtonParent = targetButton[0].parentElement.parentElement
targetButtonParent.insertAdjacentHTML('afterend', `
<tr>
<td></td>
<td>
<img src="" alt="" height="42" width="42">
<a href="">
Test Product2
</a>
</td>
<td class="deleteMe">
<button type="button" class="btn btn-danger btn-sm deleteMe">x</button>
</td>
</tr>
`)
if (targetButton.hasClass('product3') || targetButton.hasClass('product2')) {
targetButton.attr("disabled", true);
}
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tableProd" style="float: left;" class="table table-bordered">
<tbody>
<tr>
<td>Product 2</td>
<td>
<button type="button" data-exists="product2" class="btn btn-primary btn-sm product2">
Add Product 2
</button>
</td>
</tr>
<tr>
<td>Product 3</td>
<td>
<button type="button" data-exists="product3" class="btn btn-primary btn-sm product3">
Add Product 3
</button>
</td>
</tr>
<tr>
<td>Product 4</td>
<td>
<button type="button" data-exists="product4" class="btn btn-primary btn-sm product4">
Add Product 4
</td>
</tr>
</tbody>
</table>
My problem is that if I delete all rows below a disabled button I cannot add any new rows again. This case is shown in the picture below:
Any suggestions how to enable the button if all rows below have been deleted?
I appreciate your replies!
I added you one new function to your javascript
function enableButton(elemId) {
console.log(document.getElementById(elemId));
if (!document.getElementById(elemId)) {
var str = elemId.split('_');
var button = $('#'+str[1]);
$('#'+str[1]).removeAttr('disabled');
}
}
and i also set ids on your html buttons
$(".btn.btn-primary.btn-sm").on("click", this.ourClickDispatcher.bind(this))
$("#tableProd").on("click", ".btn.btn-danger.btn-sm.deleteMe", this.deleteRow.bind(this))
function deleteRow(e) {
let deleteBtn = $(e.target).closest(".deleteMe");
let itemId = e.target.getAttribute('id');
deleteBtn.closest('tr').remove();
enableButton(itemId);
}
function enableButton(elemId) {
if (!document.getElementById(elemId)) {
var str = elemId.split('_');
var button = $('#'+str[1]);
$('#'+str[1]).removeAttr('disabled');
}
}
function ourClickDispatcher(e) {
let targetButton = $(e.target).closest(".btn.btn-primary.btn-sm");
let targetButtonParent = targetButton[0].parentElement.parentElement;
var elemId = 'item_'+e.target.getAttribute('id');
targetButtonParent.insertAdjacentHTML('afterend', `
<tr>
<td></td>
<td>
<img src="" alt="" height="42" width="42">
<a href="">
Test Product2
</a>
</td>
<td class="deleteMe">
<button id='`+elemId+`' type="button" class="btn btn-danger btn-sm deleteMe">x</button>
</td>
</tr>
`)
if (targetButton.hasClass('product3') || targetButton.hasClass('product2')) {
targetButton.attr("disabled", true);
}
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tableProd" style="float: left;" class="table table-bordered">
<tbody>
<tr>
<td>Product 2</td>
<td>
<button type="button" id='btn2' data-exists="product2" class="btn btn-primary btn-sm product2">
Add Product 2
</button>
</td>
</tr>
<tr>
<td>Product 3</td>
<td>
<button type="button" id='btn3' data-exists="product3" class="btn btn-primary btn-sm product3">
Add Product 3
</button>
</td>
</tr>
<tr>
<td>Product 4</td>
<td>
<button type="button" id='btn4' data-exists="product4" class="btn btn-primary btn-sm product4">
Add Product 4
</button>
</td>
</tr>
</tbody>
</table>
</body>
</html>
Just add $(".btn.btn-primary.btn-sm").attr("disabled", false); at the end of deleteRow method.
$(".btn.btn-primary.btn-sm").on("click", this.ourClickDispatcher.bind(this))
$("#tableProd").on("click", ".btn.btn-danger.btn-sm.deleteMe", this.deleteRow.bind(this))
function deleteRow(e) {
let deleteBtn = $(e.target).closest(".deleteMe");
deleteBtn.closest('tr').remove();
$(".btn.btn-primary.btn-sm").attr("disabled", false);
}
function ourClickDispatcher(e) {
let targetButton = $(e.target).closest(".btn.btn-primary.btn-sm")
let targetButtonParent = targetButton[0].parentElement.parentElement
targetButtonParent.insertAdjacentHTML('afterend', `
<tr>
<td></td>
<td>
<img src="" alt="" height="42" width="42">
<a href="">
Test Product2
</a>
</td>
<td class="deleteMe">
<button type="button" class="btn btn-danger btn-sm deleteMe">x</button>
</td>
</tr>
`)
if (targetButton.hasClass('product3') || targetButton.hasClass('product2')) {
targetButton.attr("disabled", true);
}
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tableProd" style="float: left;" class="table table-bordered">
<tbody>
<tr>
<td>Product 2</td>
<td>
<button type="button" data-exists="product2" class="btn btn-primary btn-sm product2">
Add Product 2
</button>
</td>
</tr>
<tr>
<td>Product 3</td>
<td>
<button type="button" data-exists="product3" class="btn btn-primary btn-sm product3">
Add Product 3
</button>
</td>
</tr>
<tr>
<td>Product 4</td>
<td>
<button type="button" data-exists="product4" class="btn btn-primary btn-sm product4">
Add Product 4
</td>
</tr>
</tbody>
</table>

Change html from place

I want to change a row from a table to another but I want to replace the addBtn for a removeBtn.
dataTableTeamMembers is the other table
$('.addBtn').click(function() {
var row = $(this).closest('tr');
console.log(row[1]);
$('#dataTableTeamMembers tbody').append(row);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr class="text-center hover-table odd" role="row">
<td class="sorting_1"><img class="avatarImage" src="data:image/jpg;base64,iVBORw"></td>
<td>johns</td>
<td>John Smith</td>
<td>Member</td>
<td>
<button type="button" class="btn btn-primary addBtn"> Add</button>
</td>
</tr>
update your js code with this.
$('.addBtn').click(function () {
var row = $(this).closest('tr');
console.log(row[0]);
$('#dataTableTeamMembers tbody').append(row[0].innerHTML);
});
$('.addBtn').click(function() {
var row = $(".tbl .tbltr").html();
console.log(row[1]);
$('.tbl').append(row);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class='tbl'>
<tr class="text-center hover-table odd tbltr" role="row">
<td class="sorting_1"><img class="avatarImage" src="data:image/jpg;base64,iVBORw"></td>
<td>johns</td>
<td>John Smith</td>
<td>Member</td>
<td>
<button type="button" class="btn btn-primary addBtn"> Add</button>
</td>
</tr>
</table>

Get ID of the specific button that is clicked.

I have a table and inside the table one of the column contains a button and for each row the button id will be different. The id is data-binded using angular {{}}. on the button element i have a function called MarkasRead() that will be called on click. When i try to retrieve the id for it it shows undefined and i really need that id inside the function call to do more work.
Listed is the table code and function call.
<table *ngIf="receivedMessages?.length > 0;else noReceivedMessages" class="table table-responsive table-bordered animated bounceIn" style="table-layout: fixed;width:100%; word-wrap:break-word;">
<thead>
<tr>
<th></th>
<th>From</th>
<th>Date</th>
<th>Subject</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody *ngFor="let message of receivedMessages">
<tr *ngIf="message.mDeleted == '0' ">
<td><i style="color:red" class="fa fa-exclamation" aria-hidden="true"></i></td>
<td> {{message.messageFrom}}</td>
<td> {{message.createdDate}}</td>
<td> {{message.subject}}</td>
<td><a style="width:100%;background-color:tomato;color:white" [routerLink]="['/message/'+message.$key]" href="" class="btn">
<i class="fa fa-arrow-circle-o-right"></i> Details</a></td>
<td> <button id="{{message.$key}}" *ngIf="message.readStatus == '0'" type="submit" class="btn btn-success" (click)="MarkasRead()">Mark as Read</button>
</td>
</tr>
</tbody>
</table>
MarkasRead(){
alert(this.id); // or alert($(this).attr('id'));
}
To do this, you need to pass the id as a parameter to the MarkasRead function as "MarkasRead(message.$key)" and then define the function underneath as:
function MarkasRead(value)
{
alert(value);
}
You can do like this.Pass the $event object from the button event handler
<button id="{{message.$key}}" *ngIf="message.readStatus == '0'" type="submit" class="btn btn-success" (click)="MarkasRead($event)">Mark as Read</button>
In component
MarkasRead(event) {
var target = event.target || event.srcElement || event.currentTarget;
var elemId = target.attributes.id;
}
<button id="{{message.$key}}" *ngIf="message.readStatus == '0'" type="submit" class="btn btn-success" (click)="MarkasRead($event)">Mark as Read</button>
MarkasRead(event){
var target = event.target || event.srcElement || event.currentTarget;
var idAttr = target.attributes.id;
}
You can define a parameter at MarkasRead function and pass this
function MarkasRead(el) {
alert(el.id)
}
(click)="MarkasRead(this)"
try changing
(click)="MarkasRead()"
to
(click)="MarkasRead(event)"
And using function
function MarkasRead(e) {
alert(e.target.id);
}
<table *ngIf="receivedMessages?.length > 0;else noReceivedMessages" class="table table-responsive table-bordered animated bounceIn" style="table-layout: fixed;width:100%; word-wrap:break-word;">
<thead>
<tr>
<th></th>
<th>From</th>
<th>Date</th>
<th>Subject</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody *ngFor="let message of receivedMessages">
<tr *ngIf="message.mDeleted == '0' ">
<td><i style="color:red" class="fa fa-exclamation" aria-hidden="true"></i></td>
<td> {{message.messageFrom}}</td>
<td> {{message.createdDate}}</td>
<td> {{message.subject}}</td>
<td><a style="width:100%;background-color:tomato;color:white" [routerLink]="['/message/'+message.$key]" href="" class="btn">
<i class="fa fa-arrow-circle-o-right"></i> Details</a></td>
<td> <button id="{{message.$key}}" *ngIf="message.readStatus == '0'" type="submit" class="btn btn-success" (click)="MarkasRead({message.$key)">Mark as Read</button>
</td>
</tr>
</tbody>
</table>
MarkasRead(id) {
alert(id)
}

HTML - Get row Id by pressing a Button inside same row

Supposing I have an HTML Table and each row has Some data, an Update and a Delete Button. I want, by clicking on the Update Button, to retrieve every data THIS SPECIFIC ROW has. I have searched for other examples but they most of them just traversed through a column by using a column id and just printed every cell data they found. I need, upon pressing the update Button, to retrieve all the current cell data this row has. How can I do that?
JS Fiddle HERE
Could not properly indent code after trying for more than 30mins so I gave up
You can change your html button from:
<button type="button" class="btn btn-danger" onclick="getConfirmation();">Delete</button>
to:
<button type="button" class="btn btn-danger" onclick="getConfirmation(this);">Delete</button>
^^^^
Adding the this keyword to the function you are passing the current button. Now, in order to get the corresponding row it's enough you use jQuery.closest():
var row = $(ele).closest('tr');
or with plain js .closest()
var row = ele.closest('tr');
For the update buttons you can add the click handler:
$('#employees-table tbody button.btn.btn-warning').on('click', function(e) {
or with plain js .querySelectorAll():
document.querySelectorAll('#employees-table tbody button.btn.btn-warning').forEach.....
The jQuery snippet:
window.getConfirmation = function(ele){
var retVal = confirm("Are you sure you want to delete ?");
if( retVal == true ){
alert("User wants to delete!");
var row = $(ele).closest('tr');
row.remove();
return true;
}
else{
alert ("User does not want to delete!");
return false;
}
}
$('#employees-table tbody button.btn.btn-warning').on('click', function(e) {
var row = $(this).closest('tr');
console.log('TR first cell: ' + row.find('td:first').text());
})
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="container">
<h2>Employees</h2>
<table id="employees-table" class="table table-hover table-responsive">
<thead>
<tr>
<th>Id</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
<th>Born</th>
<th>Country</th>
<th>Department</th>
<th class="text-center">Update Row</th>
<th class="text-center">Delete Row</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>John</td>
<td>John</td>
<td>vas#gmail.com</td>
<td>1976</td>
<td>USA</td>
<td>Michigan</td>
<td class="text-center">
<button type="button" class="btn btn-warning">Update</button>
</td>
<td class="text-center">
<g:link controller="employee" action="deleteRecord">
<button type="button" class="btn btn-danger" onclick="getConfirmation(this);">Delete</button>
</g:link>
</td>
</tr>
<tr>
<td>2</td>
<td>Mark</td>
<td>Twain</td>
<td>va1122s#gmail.com</td>
<td>1965</td>
<td>England</td>
<td>London</td>
<td class="text-center">
<button type="button" class="btn btn-warning">Update</button>
</td>
<td class="text-center">
<g:link controller="employee" action="deleteRecord">
<button type="button" class="btn btn-danger" onclick="getConfirmation(this);">Delete</button>
</g:link>
</td>
</tr>
</tbody>
</table>
</div>
As per Hossein Asmand comment (How can I do this using only Javascript?) a full js solution follows:
window.getConfirmation = function(ele){
var retVal = confirm("Are you sure you want to delete ?");
if( retVal == true ){
var row = ele.closest('tr');
console.log("User wants to delete: " + row.cells[0].textContent);
row.remove();
return true;
}
else{
console.log("User does not want to delete!");
return false;
}
}
document.querySelectorAll('#employees-table tbody button.btn.btn-warning').forEach(function(ele, idx) {
ele.addEventListener('click', function(e) {
var row = this.closest('tr');
console.log('TR first cell: ' + row.cells[0].textContent);
});
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
<div class="container">
<h2>Employees</h2>
<table id="employees-table" class="table table-hover table-responsive">
<thead>
<tr>
<th>Id</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
<th>Born</th>
<th>Country</th>
<th>Department</th>
<th class="text-center">Update Row</th>
<th class="text-center">Delete Row</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>John</td>
<td>John</td>
<td>vas#gmail.com</td>
<td>1976</td>
<td>USA</td>
<td>Michigan</td>
<td class="text-center">
<button type="button" class="btn btn-warning">Update</button>
</td>
<td class="text-center">
<g:link controller="employee" action="deleteRecord">
<button type="button" class="btn btn-danger" onclick="getConfirmation(this);">Delete</button>
</g:link>
</td>
</tr>
<tr>
<td>2</td>
<td>Mark</td>
<td>Twain</td>
<td>va1122s#gmail.com</td>
<td>1965</td>
<td>England</td>
<td>London</td>
<td class="text-center">
<button type="button" class="btn btn-warning">Update</button>
</td>
<td class="text-center">
<g:link controller="employee" action="deleteRecord">
<button type="button" class="btn btn-danger" onclick="getConfirmation(this);">Delete</button>
</g:link>
</td>
</tr>
</tbody>
</table>
</div>
To to retrieve data in row after pressing button Update
<button type="button" class="btn btn-warning" onclick="getData(this)">
window.getData = function(val) {
let arr= [];
val.parentNode.parentNode.querySelectorAll('td').forEach(item=>{
if (item.getAttribute('class') != "text-center") {
arr.push(item.innerHTML)
}
},this)
console.log(arr); //["1", "John", "John", "vas#gmail.com", "1976", "USA", "Michigan"]
}
The answer from #gaetanoM will be the accepted one. If anyone wants a way not only to get only the id, but full row data, you may try this:
HTML CODE:
Change this:
<td>1</td>
<td>John</td>
<td>John</td>
<td>vas#gmail.com</td>
<td>1976</td>
<td>USA</td>
<td>Michigan</td>
to this:
<td class="table_id">23</td>
<td class="table_firstName">John</td>
<td class="table_lastName">John</td>
<td class="table_email">vas#gmail.com</td>
<td class="table_born">1976</td>
<td class="table_country">USA</td>
<td class="table_departmentId">Michigan</td>
JAVASCRIPT CODE:
Change this:
$('#employees-table tbody button.btn.btn-warning').on('click', function(e) {
var row = $(this).closest('tr');
console.log('TR first cell: ' + row.find('td:first').text());
})
to this:
$('#employees-table tbody button.btn.btn-warning').on('click', function(e) {
var id = $(this).closest('tr').find('.table_id').text();
console.log("Id = " + id);
var firstname = $(this).closest('tr').find('.table_firstName').text();
console.log("First Name = " + firstname);
var lastname = $(this).closest('tr').find('.table_lastName').text();
console.log("Last Name = " + lastname);
var email = $(this).closest('tr').find('.table_email').text();
console.log("Email = " + email);
var born = $(this).closest('tr').find('.table_born').text();
console.log("Born = " + born);
var country = $(this).closest('tr').find('.table_country').text();
console.log("Country = " + country);
var department = $(this).closest('tr').find('.table_departmentId').text();
console.log("Department = " + department);
})
See the results in THIS fiddle.
Thanks again to everyone who contributed in finding an answer!!!

Issue in recursive loop : JQuery

About the below code
I am trying to delete the roles and it's child roles recursively in Js. In the below Html: data-id="2" is RoleID and data-parentid="1" is Parent Role.
Problem
When debugger comes at last row, it does not go back to its parent row which is already traversed in the loop.
Am I missing anything?
Html Part
<table id="RoleList" class="table table-bordered">
<tbody>
<tr data-id="15">
<td>under first</td>
<td>first</td>
<td>Yes</td>
<td>
<button class="DeleteRole btn btn-primary btn-xs">Delete</button>
</td>
</tr>
<tr data-id="16" data-parentid="15">
<td>Second</td>
<td>under first</td>
<td>Yes</td>
<td>
<button class="DeleteRole btn btn-primary btn-xs">Delete</button>
</td>
</tr>
<tr data-id="17" data-parentid="16">
<td>under second</td>
<td>Second</td>
<td>Yes</td>
<td>
<button class="DeleteRole btn btn-primary btn-xs">Delete</button>
</td>
</tr>
</tbody>
</table>
JS Part
function RemovedDeletedRoles(RoleID) {
var Roles = $("#RoleList").find("tr[data-parentID='" + RoleID + "']");
$.each(Roles, function(index, row) {
var ID = $(row).attr("data-id");
var childRoles = $("#RoleList").find("tr[data-parentID='" + ID + "']");
if(childRoles.length === 0) {
$(row).remove();
}
else {
RemovedDeletedRoles($(row).attr("data-id"));
}
});
}
DOM Ready Event
$(document).on("click", ".DeleteRole", function() {
var deleteButton = $(this);
var roleID = $(deleteButton).parent().parent().attr("data-id");
RemovedDeletedRoles(roleID);
$(deleteButton).parent().parent().remove();
});
this is my code that work fine:
<table id="RoleList" class="table table-bordered">
<tbody>
<tr data-id="15">
<td>under first</td>
<td>first</td>
<td>Yes</td>
<td>
<button class="DeleteRole btn btn-primary btn-xs">Delete</button>
</td>
</tr>
<tr data-id="16" data-parentid="15">
<td>Second</td>
<td>under first</td>
<td>Yes</td>
<td>
<button class="DeleteRole btn btn-primary btn-xs">Delete</button>
</td>
</tr>
<tr data-id="17" data-parentid="16">
<td>under second</td>
<td>Second</td>
<td>Yes</td>
<td>
<button class="DeleteRole btn btn-primary btn-xs">Delete</button>
</td>
</tr>
</tbody>
</table>
//direction 0:remove children, 1:remove parents
function RemoveRoles(roleId, direction) {
direction=direction || 0; //remove by defautl remove children
//alert("RoleId:"+roleId+" - direction->"+(direction==0?"children":"parents"));
var $tr=$("#RoleList").find("tr[data-id='" + roleId + "']");
var parentId=$tr.data("parentid");
var itemsToRemove = [];
if(direction==0){
itemsToRemove=$("#RoleList").find("tr[data-parentid='" + roleId + "']");
}else{
itemsToRemove=$("#RoleList").find("tr[data-id='" + parentId + "']");
}
//alert(itemsToRemove.length);
$tr.remove();
$.each(itemsToRemove, function(index, item) {
var id = $(item).data("id");
RemoveRoles(id, direction);
});
}
$(document).on("click", ".DeleteRole", function() {
var deleteButton = $(this);
var roleID = $(deleteButton).parent().parent().attr("data-id");
RemoveRoles(roleID, 1);
$(deleteButton).parent().parent().remove();
});
Try it

Categories

Resources