I have a edit button and delete button in every rows in the table. I want to find out which row data I have selected when I clicked on to the edit/delete button so that I could do the editing/delete and then update it into my database.
Could anyone guide me out on this?
app.js
app.controller('trackingController', function(....) {
var scope = $scope;
scope.dtInstance = {};
scope.persons = {};
// create a message to display in our view
scope.message = 'Welcome to Tracking Page';
console.log("Tracking");
scope.dtOptions = DTOptionsBuilder.newOptions().withPaginationType('full_numbers').withOption('order', [0, 'asc']);
scope.dtColumnDefs = [
DTColumnDefBuilder.newColumnDef(3).notSortable()
];
$resource('data.json').query().$promise.then(function(persons) {
scope.persons = persons;
});
scope.deleteRow = function() {
console.log("deleteRow");
scope.log = 'You are trying to deleteRow the row: ';
}
scope.editRow = function() {
console.log("edit");
scope.log = 'You are trying to edit the row: ';
}
});
index.html
<p class="text-danger"><strong>{{ log }}</strong></p>
<table class="table table-striped table-bordered" datatable="ng" dt-options="dtOptions" dt-column-defs="dtColumnDefs" dt-instance="dtInstance">
<thead>
<tr>
<th>ID</th>
<th>FirstName</th>
<th>LastName</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="person in persons">
<td>{{ person.id }}</td>
<td>{{ person.firstName }}</td>
<td>{{ person.lastName }}</td>
<td>
<div class="btn-group">
<button type="button" class="btn btn-default btn" ng-click="editRow();"><i class="glyphicon glyphicon-pencil"></i></button>
<button type="button" class="btn btn-default btn" ng-click="deleteRow();"><i class="glyphicon glyphicon-trash"></i></button>
</div>
</td>
</tr>
</tbody>
</table>
In case you need to know which person is being clicked
app.controller('trackingController', function(....) {
var scope = $scope;
scope.dtInstance = {};
scope.persons = {};
// create a message to display in our view
scope.message = 'Welcome to Tracking Page';
console.log("Tracking");
scope.dtOptions = DTOptionsBuilder.newOptions().withPaginationType('full_numbers').withOption('order', [0, 'asc']);
scope.dtColumnDefs = [
DTColumnDefBuilder.newColumnDef(3).notSortable()
];
$resource('data.json').query().$promise.then(function(persons) {
scope.persons = persons;
});
scope.deleteRow = function(person) {
console.log(person);
scope.log = 'You are trying to deleteRow the row: ';
}
scope.editRow = function(person) {
console.log(person);
scope.log = 'You are trying to edit the row: ';
}
});
<p class="text-danger"><strong>{{ log }}</strong></p>
<table class="table table-striped table-bordered" datatable="ng" dt-options="dtOptions" dt-column-defs="dtColumnDefs" dt-instance="dtInstance">
<thead>
<tr>
<th>ID</th>
<th>FirstName</th>
<th>LastName</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="person in persons">
<td>{{ person.id }}</td>
<td>{{ person.firstName }}</td>
<td>{{ person.lastName }}</td>
<td>
<div class="btn-group">
<button type="button" class="btn btn-default btn" ng-click="editRow(person);"><i class="glyphicon glyphicon-pencil"></i></button>
<button type="button" class="btn btn-default btn" ng-click="deleteRow(person);"><i class="glyphicon glyphicon-trash"></i></button>
</div>
</td>
</tr>
</tbody>
</table>
Related
I have a question with data passing to component using #Input(). When i have a list component that contains some data. When i click edit an view button it loads some component. in my detailComponent:
#Input() serviceTimeGoal: IServiceTimeGoal;
And my update component same as detail. But detail component works fine. But update component receives no data. Here is i am opening modal:
<table
class="table table-striped table-bordered table=hover"
aria-describedby="page-heading"
>
<thead>
<tr>
<th scope="col"><span>Үүсгэсэн огноо</span></th>
<th scope="col"><span>Үүсгэсэн хэрэглэгч</span></th>
<th scope="col"><span>Шинэчилсэн огноо</span></th>
<th scope="col"><span>Шинэчилсэн хэрэглэгч</span></th>
<th scope="col"><span>Идэвхитэй</span></th>
<th scope="col"><span>Хугацаа</span></th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr *ngFor="let serviceTimeGoal of serviceTimeGoals; let i = index">
<td>{{ serviceTimeGoal.createdAt | dateFormatPipe }}</td>
<td>{{ serviceTimeGoal.createdBy }}</td>
<td>{{ serviceTimeGoal.updatedAt | dateFormatPipe }}</td>
<td>{{ serviceTimeGoal.updatedBy }}</td>
<td>{{ serviceTimeGoal.enabled }}</td>
<td>{{ serviceTimeGoal.time }}</td>
<td class="text-right">
<div class="btn-group">
<button
type="submit"
(click)="
openModal(serviceTimeGoal, 'service-time-goal', $event)
"
class="btn btn-info btn-sm"
>
<i class="icon-eye"></i>
</button>
<button
type="submit"
class="btn btn-primary btn-sm"
(click)="
openModal(serviceTimeGoal, 'update-service-time', $event)
"
>
<i class="icon-pencil"></i>
</button>
<button
type="submit"
[routerLink]="[
'/service-time-goal',
{
outlets: {
popup: serviceTimeGoal.id.branchId + '/delete'
}
}
]"
replaceUrl="true"
queryParamsHandling="merge"
class="btn btn-danger btn-sm"
>
<i class="icon-bin"></i>
</button>
</div>
</td>
</tr>
</tbody>
</table>
<!-- Update component -->
<qms-modal id="update-service-time">
<qms-service-time-goal-update
[serviceTimeGoal]="serviceTimeGoal"
></qms-service-time-goal-update>
</qms-modal>
<!-- Detail component -->
<qms-modal id="service-time-goal">
<qms-service-time-goal-detail
[serviceTimeGoal]="serviceTimeGoal"
></qms-service-time-goal-detail>
</qms-modal>
And in my ts file:
openModal(serviceTimeGoal: IServiceTimeGoal, id: string, e: any) {
this.singleData = serviceTimeGoal;
this.modalService.open(id);
e.stopPropagation();
}
What am i doing wrong any advice ?
EDIT:
updateComponent:
#Input() serviceTimeGoal: IServiceTimeGoal;
ngOnInit() {
this.isSaving = false;
this.updateForm(this.serviceTimeGoal);
}
updateForm(serviceTimeGoal: IServiceTimeGoal) {
console.log(serviceTimeGoal);
this.editForm.patchValue({
cat: serviceTimeGoal.id.cat,
reg: serviceTimeGoal.id.reg,
loc: serviceTimeGoal.id.loc,
name: serviceTimeGoal.id.name,
tx1: serviceTimeGoal.id.tx1,
tx2: serviceTimeGoal.id.tx2,
tx3: serviceTimeGoal.id.tx3,
tx4: serviceTimeGoal.id.tx4,
createdBy: serviceTimeGoal.createdBy,
updatedBy: serviceTimeGoal.updatedBy,
enabled: serviceTimeGoal.enabled,
time: serviceTimeGoal.time
});
}
detailComponent:
#Input() serviceTimeGoal: IServiceTimeGoal;
Update:
Detail:
If you are going to share same data between multiple components, I think using a shared service will be more efficient. You can find some sample code snippets here.
Why am I getting same value in all rows of table. Table has rows and when row is clicked another row opens with additional information and every row contains same data like last clicked row. Probably it is cos I am saving data in same object, but I really don't know how to solve it. I am getting data from json files with factor, so you don't get confused, where my data is coming from. Here is the code. Thank you very much.
'use strict';
angular.module('sbAdminApp')
.controller('TreeTableCtrl', TreeTableCtrl);
function TreeTableCtrl($scope, $http, factor) {
$scope.nonCollapsedUser = [];
var getUsers = function () {
factor.getUse().then(function (response) {
$scope.users = response.data;
});
};
getUsers();
var getUsersInfo = function () {
factor.getChi().then(function (response) {
$scope.child = response.data;
console.log($scope.child);
});
};
getUsersInfo();
$scope.togglePerson = function (index) {
$scope.nonCollapsedUser.push(index);
$scope.newObj=$scope.child[index];
console.log($scope.newObj);
};
$scope.hidePerson = function (index)
{
for(var i=0; i<$scope.nonCollapsedUser.length; i++){
if($scope.nonCollapsedUser[i] === index){
$scope.nonCollapsedUser.splice(i, 1);
}
}
};
}
<div class="panel panel-default" style="background: #fcf8e3">
<div class="panel-body">
<table st-safe-src="leads" class="table table-hover">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody ng-repeat="user in users track by $index">
<tr>
<td>{{user.id}}</td>
<td>{{user.name}}</td>
<td>{{user.lastName}}</td>
<td>
<button ng-if="nonCollapsedUser.indexOf($index) == -1" class="btn" ng-click="togglePerson($index)">
<i class="fa fa-arrow-down"></i></button>
<button ng-if="nonCollapsedUser | contains:$index" class="btn" ng-click="hidePerson($index)"><i
class="fa fa-arrow-up"></i></button>
</td>
</tr>
<tr ng-if="nonCollapsedUser | contains:$index">
<div>
<td>{{newObj.address}}</td>
<td>{{newObj.mobNumb}}</td>
</div>
</tr>
</table>
</td>
</tr>
</tbody>
</table>
</div>
</div>
According to your description,
I assume your users, child arrays like this
$scope.users =[
{"id":1,"name":"Mirko","lastName":"Spriko"},
{"id":2,"name":"Pero","lastName":"Peric"},
{"id":3,"name":"Marko","lastName":"Prezime"}
];
$scope.child =[
{"address":"Address1","mobNumb":"47423756324"},
{"address":"Address2","mobNumb":"73454635545"},
{"address":"Address3","mobNumb":"87464343648"}
];
First you need to map child to users
angular.forEach($scope.users, function(value,key){
value.child =$scope.child[key];
});
Now you can achive your target
<table st-safe-src="leads" class="table table-hover">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Last Name</th>
<th></th>
</tr>
</thead>
<tbody ng-repeat="user in users" >
<tr>
<td>{{user.id}}</td>
<td>{{user.name}}</td>
<td>{{user.lastName}}</td>
<td>
<button ng-show="nonCollapsedUser.indexOf($index) == -1" class="btn" ng-click="togglePerson($index)">
<i class="fa fa-arrow-down"></i>veiw</button>
<button ng-show="nonCollapsedUser.indexOf($index) > -1" class="btn" ng-click="hidePerson($index)"><i
class="fa fa-arrow-up"></i>hide</button>
</td>
</tr>
<tr ng-show="nonCollapsedUser.indexOf($index) > -1">
<td></td>
<td>{{user.child.address}}</td>
<td>{{user.child.mobNumb}}</td>
<td
</tr>
</table>
This is working JSFiddle
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!!!
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
I want to render the response of the http.get() function of angularJS, actually the problem is that when i use http.get in a controller function then it is not rendering response data.
View:
<div ng-app="myApp" ng-controller="dtlCtrl" >
<div class="table-responsive">
<table class="table table-striped">
<thead>
<th> Name</th>
<th >Storage</th>
<th >Credits</th>
</thead>
<tbody>
<tr ng-repeat="a in credits" >
<td>{{ a.username }}</td>
<td>{{ a.storage }}</td>
<td>{{ a.credits }}</td>
</tr>
</tbody>
</table>
<div class="clearfix"></div>
</div>
</div>
</div>
<div class="modal-footer ">
<button type="button" class="btn btn-warning btn-lg" style="width: 100%;"><span class="glyphicon glyphicon-ok-sign"></span> Update</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
JavaScript:
app.controller('dtlCtrl', function($scope, $http) {
//var count;
//window.names=" ";
//count=0;
$scope.crd=function(name) {
// alert("http://localhost:8080/ZenCameraAdmin/admin/getusercredits?username="+name);
// count=1;
$scope.credits;
window.names=name;
//alert(window.names);
$http.get("http://192.168.0.87:8080/ZenCameraAdminServices/admin/getusercredits?username="+window.names)
.success(function (response) {$scope.credits = response.credits;
//console.log(response.plans);
});
//alert(window.names);
console.log($scope.credits);
return $scope.credits;
};
});