How to select a row from dynamic table on mouseclick event - javascript

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

Related

Replace old value with new value excluding the children

The initial text of A, B, C, D, and the number need to be removed in the frontend because I require it in the backend.
The HTML structure of table row is like this:
<tr ng-repeat="(key, field) in nbd_fields" ng-show="field.enable && field.published" class="ng-scope">
<td class="ng-binding">A,B,C,D: 1 - Auswahl Wunschkarte : <b class="ng-binding">Wähle eine Option</b>
</td>
<td ng-bind-html="field.price | to_trusted" class="ng-binding"></td>
</tr>
Before Input:
Current Output:
If you notice that the selected option is also not visible. Is it because of the $(window).load() ?
Required Output:
Code that I am using:
jQuery(".ng-scope td.ng-binding:first-child").text(function(i, oldVal) {
return oldVal.replace(/^[^-]+ - /,"");
});
});
How can I make it so that it does not affect the <b> tag inside?
I used the above code for the steps heading with a different selector on the same page* and it worked because it did not have any children to alter.
I had to wrap it around $(window).load() so that the changes are applied after the table is loaded. $(document).ready() did not work with it. Not sure why?
(Edit: Modified to accommodate restated requirement in comment below.)
To strip "everything up to and including the '-'" from the text of first column table cells while leaving the rest untouched:
// strip "everything up to and including the '-'"
// from table cell contents
function stripPrefix(tblCell) {
// only evaluate first td in tr
if (tblCell.previousElementSibling) {
return;
}
const tNode = tblCell.firstChild;
// ignore if table cell is empty
if (!tNode) {
return;
}
const chars = tNode.nodeValue.split('');
const iFirstDash = chars.indexOf('-');
if (iFirstDash === -1) { return; }
tNode.nodeValue = chars.slice(iFirstDash+1).join('');
}
function stripAllPrefixes() {
const tds = document.getElementsByTagName('td');
for (const td of tds) {
stripPrefix(td);
}
}
td {
border: 1px solid gray;
}
<h4>Strip "everything up to and including the '-'" from Table Cells</h4>
<table>
<tr>
<td>A,B,C,D: 1 - Auswahl Wunschkarte : <b>Wähle eine Option</b></td>
<td></td>
</tr>
<tr>
<td>B,C,D,E: 20 - A different leader : <b>should also be stripped</b></td>
<td></td>
</tr>
<tr>
<td>Oops no dash here <b>Just checking</b></td>
<td></td>
</tr>
</table>
<button onclick="stripAllPrefixes();">Strip All</button>
It does not effect the b tag, your code is working, you just need to use the right method and do the replacement to the HTML code and not the text nodes:
jQuery(".nbd-field-header label, .nbo-summary-table .ng-binding").html(function(i, oldVal) {
return oldVal.replace(/^[^-]+ - /,"");
});

How to Remove a row from Table using angular js?

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)

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

persist node state between postbacks with jquery cookie plugin

I have the following html table
<table id="{64ED3A94-5833-4CC7-869F-CCE583B498BE}" class="ms-listviewtable"
width="100%" cellspacing="0" cellpadding="1" border="0"
xmlns:o="urn:schemas-microsoft-com:office:office" dir="none">
<tbody id="tbod23-1__" isloaded="true" style="display: none;"></tbody>
<tbody id="tbod23-2__" isloaded="true" style=""></tbody>
<tbody id="tbod23-3__" isloaded="true" style="display: none;"></tbody>
<tbody id="tbod23-4__" isloaded="true" style=""></tbody>
<tbody id="tbod23-5__" isloaded="true" style="display: none;"></tbody>
<tbody id="tbod23-6__" isloaded="true" style="display: none;"></tbody>
<tbody id="tbod23-7__" isloaded="true" style="display: none;"></tbody>
</table>
This table is autogenerated by a sharepoint xsltlistviewwebpart (didnt post in sharepoint as the question is more jquery+html related).
this is a treeview with nodes, when i expand a collapsed node it changes style from
style="display: none;"
to
style=""
The problem: the webpart does not remember which nodes were collapsed, so on each postback it resets all to expanded. What I need to do, is to remember the node state (expanded or collapsed) in a jquery cookie, and to retrieve it on postbacks (so, to persist the node state).
So far I got:
<script type="text/javascript">
_spBodyOnLoadFunctionNames.push("RememberClickedState");
function RememberClickedState()
{
var dv = $('.ms-listviewtable');
var items = [];
items = dv.find('tbody[id^="tbod"]');
$.cookie("itemListState", items);
alert(items[0]);
alert(items[1]);
}
</script>
Can anyone please provide some pointers on how to do this. Im a bit dazed and confused about the events themselves, on page_load I should save the cookie but also retrieve it somehow.
Also "items" array stored all 7 elements which is good, but when i try alert(items[0]); I get undefined.
Thank you
I suggest you to create string of this and then parse this string back... kind of like that:
var items = '';
function RememberClickedState() {
$('.ms-listviewtable tbody').each(function(){
tid = $(this).attr('id');
tvisible = $(this).is(':visible');
items += tid+':'+tvisible+','
})
//$.cookie("itemListState", items);
$('body').append(items+'<br/>');
}
function RestoreClickedState() {
//string = $.cookie("itemListState")
var string = items; //temporary
var cookies = string.split(',');
$.each(cookies, function(i, val){
val = val.split(':');
show = (val[1] == 'true' ? true:false);
item = $('.ms-listviewtable').find('#'+val[0]);
show ? item.show() : item.hide();
$('body').append('#'+val[0]+' is '+ 'display:'+show+'<br/>');
})
}
$(document).ready(function(){
RememberClickedState();
RestoreClickedState();
})
Here is DEMO:
http://jsfiddle.net/MYexv/3/

Categories

Resources