Get ID of the specific button that is clicked. - javascript

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)
}

Related

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!!!

Passing values to jquery function on click of button

I have the following table in my HTML page, I'm a newbie to Jquery
<table class="table table-hover">
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th>Start Date</th>
<th>Severity</th>
<th>Edit Data</th>
</tr>
</thead>
<tbody id="myTable">
<tr style="display: table-row;">
<td>New Rule</td>
<td>New Rule</td>
<td>2017-04-04</td>
<td>High</td>
<td>
<button class="btn btn-primary btn-sm editBtn">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
Edit
</button>
<button onclick="window.location ="/EmployeeSpringMVC/delRule/5"" data-method="delete" class="btn btn-danger btn-sm">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
Delete
</button>
</td>
</tr>
</tbody>
</table>
As you can see there is an edit button I can write a function to recognize clicks to this button as given below
$('.editBtn').click(function(){
alert("test");
});
I also need the data in the particular row for some processing in the function. How can I get this data from the table row. Please feel free to suggest if there is a better way.
I saw the question here but I did not understand this statement of the answer.
var id = $(this).attr('id');
How is the id passed to the function. What specifies the id in this.
<input id="btn" type="button" value="click" />
Because you probably need all <td> in row, except current one I would suggest to use siblings() method of closest <td>:
$('.editBtn').click(e => {
e.preventDefault();
const $td = $(e.target).closest('td');
const fields = Array.from($td.siblings('td').map((i, e) => $(e).text()));
console.log(fields);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-hover">
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th>Start Date</th>
<th>Severity</th>
<th>Edit Data</th>
</tr>
</thead>
<tbody id="myTable">
<tr style="display: table-row;">
<td>New Rule</td>
<td>New Rule</td>
<td>2017-04-04</td>
<td>High</td>
<td>
<button class="btn btn-primary btn-sm editBtn">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
Edit
</button>
<button onclick="window.location ="/EmployeeSpringMVC/delRule/5"" data-method="delete" class="btn btn-danger btn-sm">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
Delete
</button>
</td>
</tr>
</tbody>
</table>

Sort data in jQuery by specific attribute

I'm trying to sort data in jQuery by a specific attribute like following:
<table id="tableSellers" class="table table-striped jambo_table bulk_action">
<thead>
<tr class="headings">
<th class="column-title"><h4><i class="fa fa-user" style="text-align:center"></i> <span>Username</span></h4> </th>
<th></th>
<th class="column-title"> <h4><span class="glyphicon glyphicon-tasks salesClick" aria-hidden="true"></span></h4></th>
<th class="column-title"><h4><i class="fa fa-star feedbackClick"></i></h4></th>
</tr>
</thead>
<tbody class="testWrapper">
#foreach (var item in ViewBag.rezultati)
{
<tr class="test" sale=#item.SaleNumber feedback=#item.Feedback>
<td>
#item.StoreName
</td>
<td>
<button type="button" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="" value="#item.StoreName" data-original-title="Analyze competitor">
<i class="fa fa-bar-chart-o"></i>
</button>
</td>
<td>
<b>
#item.SaleNumber
</b>
</td>
<td><b>#item.Feedback</b></td>
</tr>
}
</tbody>
</table>
And this is the code I'm currently using to sort the data, but it doesn't works as I want it to:
$(".feedbackClick").click(function () {
var $wrapper = $('.testWrapper');
$wrapper.find('.test').sort(function (a, b) {
return +a.feedback - +b.feedback;
})
.appendTo($wrapper);
});
This just sorts 1 item in the whole table (or something, I'm not really sure?)
Can someone help me out with this?
Edit: Here is the rendered tr tag:
<table id="tableSellers" class="table table-striped jambo_table bulk_action">
<thead>
<tr class="headings">
<th class="column-title">
<h4><i class="fa fa-user" style="text-align:center"></i> <span>Username</span></h4> </th>
<th></th>
<th class="column-title">
<h4><span class="glyphicon glyphicon-tasks salesClick" aria-hidden="true"></span></h4></th>
<th class="column-title">
<h4><i class="fa fa-star feedbackClick"></i></h4></th>
</tr>
</thead>
<tbody class="testWrapper">
<tr class="test" sale="0" feedback="349">
<td>kansascitykittygirl</td>
<td>
<button type="button" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="" value="kansascitykittygirl" data-original-title="Analyze competitor"><i class="fa fa-bar-chart-o"></i></button>
</td>
<td>
<b>0</b>
</td>
<td><b>349</b></td>
</tr>
<tr class="test" sale="10" feedback="14250">
<td>fancaveidaho</td>
<td>
<button type="button" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="" value="fancaveidaho" data-original-title="Analyze competitor"><i class="fa fa-bar-chart-o"></i></button>
</td>
<td><b>10</b></td>
<td><b>14250</b></td>
</tr>
</tbody>
</table>
The problem is a.feedback and b.feedback are not getting feedback attribute's value. You can use $(a).attr('feedback') and $(b).attr('feedback') instead like following.
$(".feedbackClick").click(function() {
var $wrapper = $('.testWrapper');
$wrapper.find('.test').sort(function(a, b) {
return +$(b).attr('feedback') - +$(a).attr('feedback');
}).appendTo($wrapper);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tableSellers" class="table table-striped jambo_table bulk_action">
<thead>
<tr class="headings">
<th class="column-title">
Title
</th>
</tr>
</thead>
<tbody class="testWrapper">
<tr class="test" feedback="1">
<td>1111</td>
</tr>
<tr class="test" feedback="3">
<td>3333</td>
</tr>
<tr class="test" feedback="2">
<td>2222</td>
</tr>
</tbody>
</table>
<button class="feedbackClick">Sort</button>

Delete td of table htm with jquery

hi guys i have a question, i need remove a td of table, the td has a id and i try with remove(), but doesnt work this is my code in js
$('.btnEliminarLicencia').off('click');
$('.btnEliminarLicencia').on('click', function () {
$(this).parent().parent().remove();
var rlim=$('.btnEliminarRemoto').parent().parent().remove('#idLicenciaClienteR');
alert (rlim);
});
and i have two tables, in the first with the btnEliminarLicencia click remove the tr of table and in the second table delete also the td what is the first td of table , this is the code, i need delete the first table and a specific td
first table
<table class="table table-bordered tabla_licencia">
<thead>
<tr>
<th>Sucursal</th>
<th>Codigo (ID cliente)</th>
<th>Licencia</th>
<th>Caducidad</th>
<th>Estado</th>
<th style="width: 15%;"></th>
</tr>
</thead>
<tbody>
<tr>
<td data-id="318">13123</td>
<td id="id_Cliente">18865082</td>
<td>482947</td>
<td>2016-11-04</td>
<td>
<input type="checkbox" class="form-control" checked="" disabled="">
</td>
<td>
<button type="button" class="btn btn-info btnEditLicencia" style="float:right;">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
</button>
<button type="button" class="btn btn-danger btnEliminarLicencia" style="float:left;">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
</button>
</td>
</tr>
</tbody>
second table
<table class="table table-bordered tabla_remoto">
<thead>
<tr>
<th>Licencia</th>
<th>Descripcion</th>
<th>Usuario</th>
<th>Clave</th>
<th style="width: 15%;"></th>
</tr>
</thead>
<tbody>
<tr>
<td id="idLicenciaClienteR">18865082</td>
<td>Caja</td>
<td>883792</td>
<td>nim3</td>
<td>
<button type="button" class="btn btn-info btnEditRemoto" style="float:right;">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
</button>
<button type="button" class="btn btn-danger btnEliminarRemoto" style="float:left;">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
</button>
</td>
</tr>
</tbody>
in this case delete <td id='idLicenciaClienteR'>189992887</td>
as might do it, thanks
This might help you,
$('.btnEliminarLicencia').on('click', function () {
$('td#idLicenciaClienteR').remove();
});
Since id is unique in a page, you can dirctly use the id, no need to find with .parents().
Try something like this:
$('table td#id_Cliente').remove();
you can also define the class by putting .yourClass behind table

Add Table Class/Remove Table Class to rows on AJAX Request

I've created a simple table using Bootstrap and PHP which looks like this:
<table class="table table-condensed table-striped table-bordered">
<thead>
<th scope="col">Name</th>
<th scope="col">Date</th>
<th scope="col">Select</th>
</thead>
<tbody>
<tr id="RFIT1000">
<td>Penny Lane</td>
<td>10/03/2015</td>
<td colspan="2">
<button type="button" class="btn btn-success btn-sm">Yes</button>
</td>
</tr>
<tr id="RFIT1001">
<td>Fred Kruger</td>
<td>18/01/2016</td>
<td colspan="2">
<button type="button" class="btn btn-success btn-sm">Yes</button>
</td>
</tr>
<tr id="RFIT1002">
<td>Bob Hope</td>
<td>09/08/2016</td>
<td colspan="2">
<button type="button" class="btn btn-success btn-sm">Yes</button>
</td>
</tr>
</tbody>
</table>
I have a script that runs when you click the "Yes" button to select a row to add a class to the selected table row - this is working well - to highlight the selected row green. The user is only allowed to select one row before they submit the form so I now need to modify this so that when they select a table row it highlights the selected row in green but removes any table row classes for all other table rows in the table.
Here's my script at the moment:
$(document).ready(function() {
$('button.btn-success').click(function() {
var refreshItemID = $(this).closest('tr').attr('id');
console.log(refreshItemID);
// Create a reference to $(this) here:
$this = $(this);
$.post('updateStaffSelection.php', {
refreshItemID: refreshItemID,
selectionType: 'yes'
}, function(data) {
data = JSON.parse(data);
if (data.error) {
console.log(data);
console.log('something was wrong with the ajax request');
$this.closest('tr').addClass("warning");
//make alert visible
$("#alert_ajax_error").show();
return; // stop executing this function any further
} else {
console.log('update successful - success add class to table row');
$this.closest('tr').addClass("success");
$this.closest('tr').removeClass("danger");
//$(this).closest('tr').attr('class','success');
}
}).fail(function(xhr) {
console.log('ajax request failed');
// no data available in this context
$this.closest('tr').addClass("warning");
//make alert visible
$("#alert_ajax_error").show();
});
});
});
I'm hoping it's possible to extend this to also remove any classes for the non selected row so that only the selected row has the success class added but not sure where to start here.
Remove the relevant classes that you need once the button was clicked from all of the tr elements in the table, and add the relevant class only to the specific tr.
$(function() {
$('button.btn-success').click(function() {
// Remove the classes from all of the TR elements
$(this).parents('table').find('tr').removeClass('success warning danger');
// Add the class only to the specific TR element
$(this).parents('tr').addClass('success');
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap-theme.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<table class="table table-condensed table-striped table-bordered">
<thead>
<th scope="col">Name</th>
<th scope="col">Date</th>
<th scope="col">Select</th>
</thead>
<tbody>
<tr id="RFIT1000">
<td>Penny Lane</td>
<td>10/03/2015</td>
<td colspan="2">
<button type="button" class="btn btn-success btn-sm">Yes</button>
</td>
</tr>
<tr id="RFIT1001">
<td>Fred Kruger</td>
<td>18/01/2016</td>
<td colspan="2">
<button type="button" class="btn btn-success btn-sm">Yes</button>
</td>
</tr>
<tr id="RFIT1002">
<td>Bob Hope</td>
<td>09/08/2016</td>
<td colspan="2">
<button type="button" class="btn btn-success btn-sm">Yes</button>
</td>
</tr>
</tbody>
</table>

Categories

Resources