How to Remove a row from Table using angular js? - javascript

I am using Angular http service to perform a DELEET operation , Its working fine , after deleting the data record I have to remove that row also from table .
Below is my code for all that
$scope.DeleteSchedule = function (recordId) {
var v =$window.confirm('Are you sure you want to delete ?');
if (v == true) {
var row = '#row' + recordId;
var table = 'table #tbl_Schedule_Delete tr ' + row;
$http({
url: '#Url.Action("DeleteSchedule", "Admin")',
method: "DELETE",
params: {
recordId: recordId
}
}).then(function mySuccess(response) {
alert('Row Deleted Successfully');
angular.element(document.querySelector(table)).remove();
//$('table #tbl_Schedule_Delete tr' + row).remove();
}, function myError(response) {
$window.alert('Warning! It failed.');
});
}
}
Refrence to jQuery remove() seems to do nothing
value of variable table will be 'table #tbl_Schedule_Delete tr #row35'
angular.element(document.querySelector(table)).remove();
I checked console log and there is no error or warning . How to do this in angular JS
Update 1 :
Below is Table Mark Up
<tr id="row34" role="row" class="odd">
<td id="delete34" class="sorting_1">
<a id="deletebtn_34" ng-click="DeleteSchedule('34')"><i class="fa fa-times fa-lg" aria-hidden="true" style="color:#e90029"></i></a>
</td>
<td>34</td>
<td>11956</td>
<td>Tota Ram</td>
<td>04-10-2017</td>
<td>02-12-2017</td>
<td>Haryana</td>
<td>Badaun</td>
<td>03-11-2017</td>
</tr>

I wouldn't delete the row using angular.element but show/hide the row with ng-if of ng-show.
<tr id="row34" role="row" class="odd" ng-show="!deleted[34]">
in combination with:
after deletion in your controller:
scope.deleted[recordId] = true;

The problem is with your selection query. The selector
table #tbl_Schedule_Delete tr #row35
actually matches the following HTML structure:
<table>
<any-element id="#tabl_Schedule_Delete">
<tr>
<any-element id="#row35"></any-element>
</tr>
</any-element>
</table>
As you can see, this doesn't match your HTML structure. This is because your selection query contains a couple of whitespaces when matching elements and ids. This causes it to look for child elements when matching the ids.
To fix it, your selector should instead look like this:
var table = 'table#tbl_Schedule_Delete tr' + row;
// Notice the lack of whitespaces after 'table' and 'tr'
Side note: using document.querySelector() inside angular.element() is redundant. You could simply use angular.element(table) since, angular.element is equivalant to using $(selector) (it's actually exactly the same, in case that you have jquery loaded)

Related

datatables rows().ids() return undefined

In my datatable I set the ID attribute for rows:
'createdRow': function (row, data, dataIndex) {
$(row).attr('id', data.json.unid);
}
Under a button I want to grab the ID's:
action: function () {
var count = table
.rows({
selected: true
})
.ids();
alert("id:s" + count)
for (i = 0; i < count.length; i++) {
alert("id:" + count[i])
}
rpcService
.setIds(count
.toArray());
}
In the alert I get for the ID "undefined".
Here is what a row looks like:
<tr id="FF97C3CFC0F5FA76C12583D1003EA028" role="row" class="odd selected">
<td class=" select-checkbox"> </td>
<td>Anne Weinstein</td>
<td>ORP B</td>
<td>Anne Weinstein</td>
<td>s41660</td>
</tr>
What am I doing wrong?
You are setting IDs on the elements in the DOM, but the .ids() method is not supposed to return those.
https://datatables.net/reference/api/rows().ids()
Important This method does not read the DOM id for the tr elements, but rather gets the row id from the row's data source (location specified by rowId).
You would need to provide the IDs upfront in your data source already, so that you can match them via the rowId option, to get what datatables considers a “row id”.

Iterate through selected rows in Datatables

I'm using Datatables and mark ids of my table with
<tr data-id='1'>
tags. I want to get the ids of selected rows. I tried this but it doesn't seem to work:
var $issueID = $(my_table.rows('.selected').nodes()).data('id');
$.each($issueID, function (value, index ) {
alert(value);
});
If I want to do it for a single row it works fine if I use
row().node()
but I can't get it right for many rows.
This should do the trick:
var selectedIds = [];
var my_table = $('#my_table').DataTable();
my_table.rows('.selected').every( function() {
selectedIds.push(this.data().id);
});
As Mike mentioned in a comment, notice that a capital D which is used to initialise the DataTable here. $().DataTable() returns a DataTables API instance, while $().dataTable() will also initialise a DataTable, but returns a jQuery object.
While searching for the same answer I came across this article. I modified the code in your question to find a working solution.
var inactiveRecord = $(my_table.rows('.selected').nodes());
$.each(inactiveRecord, function (idx, value) {
alert($(value).data('id'));
});
You should use a Class to do this in addition to your data-id.
JQUERY
$('.row').each( function() {
var value = $(this).attr('data-id');
alert(value);
})
HTML
<tr class="row" data-id="1">
<td></td>
</tr>
<tr class="row" data-id="2">
<td></td>
</tr>
<tr class="row" data-id="3">
<td></td>
</tr>
or without a Class you could just use
$('tr').each( function() {
var value = $(this).attr('data-id');
alert(value);
})
I recommend adding a class to tr so you don't accidentally get it mixed up with other rows that may not need to be counted.

Unable to add style class or access elements' attributes from jquery each loop

I have a table, which looks like this:
<table id="ctoTable" class="table table-bordered">
<thead> ... </thead>
<tbody>
<tr></tr>
<tr id="kpi#1" class="js-editable"></tr>
<tr id="kpi#2" class="js-editable"></tr>
<tr id="kpi#3" class="js-editable"></tr>
<tr id="kpi#4" class="js-editable"></tr>
<tr id="kpi#5" class="js-editable"></tr>
<tr id="kpi#6" class="js-editable"></tr>
<tr id="kpi#7" class="js-editable"></tr>
<tr id="kpi#8" class="js-editable"></tr>
<tr id="kpi#9" class="js-editable"></tr>
<tr id="kpi#76" class="js-editable"></tr>
<tr id="kpi#77" class="js-editable"></tr>
<tr></tr>
</tbody>
and I would like to be make some kind of filter which allows me to show and hide some of the rows. I was pretty sure that I could do it on this way but unfortunately it does not work. Not only that I am not able to add/remove classes, I can't event get an attribute of an th.
jQuery(document).ready(function($) {
$( "#hideRows" ).click(function() {
var rows = $('.js-editable');
$.each(rows, function(index, item) {
console.log(item);
//item.addClass("hideElement"); //try to add the class to the tr
console.log(item.attr("id")); //try to print tr id in console
});
});
});
as a result only the first row will be printed out
<tr id="kpi#1" class="js-editable"></tr>
and than the method breaks without any errors logged.
Could someone expain to me what is happening here and how could I fix this issue.
The problem is item inside the loop is a dom element reference not a jQuery object so you can't access jQuery methods directly from item.
Instead you need to get a jQuery object reference for item by passing it to jQuery like $(item) and then you can use jQuery methods like
jQuery(document).ready(function ($) {
$("#hideRows").click(function () {
var rows = $('.js-editable');
rows.each(function (index, item) {
console.log(item);
//$(item).addClass("hideElement"); //try to add the class to the tr
console.log($(item).attr("id")); //try to print tr id in console
});
});
});
But if you just want to add a class there is no need to use a loop
jQuery(document).ready(function ($) {
$("#hideRows").click(function () {
var rows = $('.js-editable');
rows.addClass("hideElement");
});
});
Also note then it is better to use .each() instead of $.each() to iterate over jQuery object.
If you write item.attr, it will return an error, because, by this way item is not a jQuery object.
Change it like this:
$(item).attr("id")
console.log($(item).attr("id")) instead of console.log(item.attr("id"))
jQuery(document).ready(function($) {
$( "#hideRows" ).click(function() {
var rows = $('.js-editable');
$.each(rows, function(index, item) {
console.log(item);
//item.addClass("hideElement"); //try to add the class to the tr
console.log($(item).attr("id")); //try to print tr id in console
});
});
});
DEMO

Cannot use fnAddData when table is empty

I'm using a table with the jquery dataTable plugin.
When I use the function fnAddData it works, except when the table is empty. Then, I get this error :
Cannot read property 'className' of undefined
This is how I add my data:
$("#table-1").dataTable().fnAddData([
data[0],
data[1],
data[2],
data[3],
data[4],
data[5],
data[6],
data[7],
data[8],
]);
And I have the same problem with fnDeleteRow with this error message:
Cannot read property 'nTr' of undefined
Here's how I use fnDeleteRow, I have no trouble when the table is not empty...
$("#table-1").dataTable().fnDeleteRow(tr)
where tr is a selector.
Am I missing something?
Here's my HTML tab with one last row :
<table id="table-1" class="table table-hover table-nomargin table-colored-header dataTable" aria-describedby="table-1_info">
<thead>
<tr role="row">
<th class="sorting" role="columnheader" tabindex="0" aria-controls="table-1" rowspan="1" colspan="1">Pays</th>
</tr>
</thead>
<tbody role="alert" aria-live="polite" aria-relevant="all">
<tr class="odd">
<td class=" sorting_1">
<div id="address23name">test</div>
</td></tr></tbody></table>
And here's my JS
$("#deleteAddressButton").click(function(){
var id = $("#deleteAddressId").val();
$.post("/Contacts/deleteAddress",
{data: id}, function(data) {
var id = $.parseJSON(data);
var tr = $("tr:has(td:has(div:contains(\"address\" + id + \"Name\")))");
$("#table-1").dataTable().fnDeleteRow(tr)
});
})
jQuery doesn't allow DataTables to access the data in the way that it prefers. In order to give it the node that it wants, you will probably need to apply [0] or .get(0) to the end of your jQuery object. That is actually what jQuery returns -- an object -- and normally exactly what you would be comfortable working with.
DataTables wants a node.
Here are some links that show the developer giving hints about how to access the data in different circumstances -- but with the same error in the 2nd link:
here
and
here
The moral of the story is that if DataTables is expecting a table "node", you need to do some extra footwork to remove the extra jQuery container that it is placed within.
Your code would, therefore, look like this and I believe should handle your error condition. Otherwise, be sure to search for your error and function name on DataTables.net. That forum is very active and helpful.
var tr = $("tr:has(td:has(div:contains(\"address\" + id + \"Name\")))");
$("#table-1").dataTable().fnDeleteRow(tr[0])
or
var tr = $("tr:has(td:has(div:contains(\"address\" + id + \"Name\")))");
$("#table-1").dataTable().fnDeleteRow(tr.get(0))
or of course, add it to the end of your lengthy $("tr:has...) statement.
Option 2:
Just hide the row you want to delete
If these ideas don't help, you may find allan's answers here insightful.
Here's a simple jsfiddle, which allows you to add a row to an empty table:
http://jsfiddle.net/7UZGM/
So what's different about your table? When you say "empty", does it still have a thead/tr/th section and an empty tbody section? These are required for datatables to work properly.
$('#dt').dataTable();
$('#btn').on('click',function() { addData(); });
function addData()
{
$("#dt").dataTable().fnAddData([
"col 1", "col 2", "col 3"]);
}

How to select a row from dynamic table on mouseclick event

How can get a row's value on mouse click or checking the checkbox preferably from the below given html table?
Here is the js for getting values for my table from a xml using spry
var ds1 = new Spry.Data.XMLDataSet("xml/data.xml", "rows/row");
var pv1 = new Spry.Data.PagedView( ds1 ,{ pageSize: 10 , forceFullPages:true, useZeroBasedIndexes:true});
var pvInfo = pv1.getPagingInfo();
Here is the Div with spry region containing the table that gets populated from pv1 (see js part)
<div id="configDiv" name="config" style="width:100%;" spry:region="pv1">
<div spry:state="loading">Loading - Please stand by...</div>
<div spry:state="error">Oh crap, something went wrong!</div>
<div spry:state="ready">
<table id="tableDg" onclick="runEffect('Highlight', 'trEven', {duration: 1000, from: '#000000', to: '#805600', restoreColor: '#805600', toggle:true}, 'Flashes a color as the background of an HTML element.')"
style="border:#2F5882 1px solid;width:100%;" cellspacing="1" cellpadding="1">
<thead>
<tr id="trHead" style="color :#FFFFFF;background-color: #8EA4BB">
<th width="2%"><input id="chkbHead" type='checkbox' /></th>
<th width="10%" align="center" spry:sort="name"><b>Name</b></th>
<th width="22%" align="center" spry:sort="email"><b>Email</b></th>
</tr>
</thead>
<tbody spry:repeat="pv1">
<tr class="trOdd"
spry:if="({ds_RowNumber} % 2) != 0" onclick="ds1.setCurrentRow('{ds_RowID}');"
style="color :#2F5882;background-color: #FFFFFF">
<td><input type="checkbox" id="chkbTest" class = "chkbCsm"></input></td>
<td width="10%" align="center"> {name}</td>
<td width="22%" align="center"> {email}</td>
</tr>
<tr class="trEven" name="trEven" id="trEven"
spry:if="({ds_RowNumber} % 2) == 0" onclick="ds1.setCurrentRow('{ds_RowID}');"
style="color :#2F5882;background-color: #EDF1F5;">
<td><input type="checkbox" class = "chkbCsm"></input></td>
<td id="tdname" width="10%" align="center"> {name}</td>
<td width="22%" align="center"> {email}</td>
</tr>
</tbody>
</table>
</div>
</div>
I am trying the below code but still I am not getting the alert and hence none of the answers are also not working. I know the syntax n all are everything correct, but i am not able to figure out what is the problem here!
//inside $(document).ready(function()
$("#chkbHead").click(function() {
alert("Hi");
});
My page has other tables too for aligning some contents. So when I use the below code it works perfectly on those tables except the one in the question. It might be the problem because there are only 2 tr in the table which gets populated by a spry dataset and hence not getting identified properly. May be, I am not sure, just trying to help improve my understanding
$('tr').click(function() {
alert("by");
});
The values of a Row you will get with:
$('#tableDg tbody tr').live( 'click', function (event) {
$(this).find('td').each( function( index, item ) {
if ( $(this).has(':checkbox') ) {
alert( $(this).find(':checkbox').val() );
} else {
alert( $(this).text() );
}
};
});
What exactly do you mean by value of a table row? You can get the inner html of a table row like this:
var html = '';
$('tr').click(function() {
html = $(this).html();
});
You can get attributes of the table row (e.g. it's Id) like so:
var id = '';
$('tr').click(function() {
id = $(this).attr('id');
});
Alternatively you can get the value of nested elements such as a text input like so:
var text = '';
$('tr').click(function() {
text = $(this).find('#myTextBox').val();
});
EDIT
This is how to change the checked attribute of a checkbox nested in a table row:
$('tr').click(function() {
$(this).find('input:checkbox').attr('checked', 'checked');
// alternatively make it unchecked
$(this).find('input:checkbox').attr('checked', '');
});
EDIT
As the table rows are being loaded dynamically - the $().click() event binding method will not work, because when you are calling it - the table rows do not exist, so the click event cannot be bound to them. Instead of using $().click use the jQuery live method:
$('tr').live('click', function() {
// do stuff
});
This binds the click event to all current table rows and all table rows that may be added in the future. See the jQuery docs here
you have to use Spry Observer,
something like this:
function funcObserver(notificationState, notifier, data) {
var rgn = Spry.Data.getRegion('configDiv');
st = rgn.getState();
if (notificationState == "onPostUpdate" && st == 'ready') {
// HERE YOU CAN USE YOUR JQUERY CODE
$('#tableDg tbody tr').click(function() {
$(this).find('input:checkbox').attr('checked', 'checked');
// alternatively make it unchecked
$(this).find('input:checkbox').attr('checked', '');
});
}
}
Spry.Data.Region.addObserver("configDiv", funcObserver);

Categories

Resources