DataTables jquery identifying row ID - javascript

I am using DataTables and capturing am img click on either edit or delete icon's. My problem is, I need to capture the row ID as well.. I tried putting the row ID in the href tag but npt able to extract it..
The current code is
$('#datatable tbody tr a.delete img').live( 'click', function (e) {
var rowID = $('a').attr('href');
alert(rowID);
if (!fancyConfirm(rowID, "Are you sure you want to delete this record?", function(ret) { alert(rowID) }))
e.preventDefault();
});
You can see the actual page at http://www(#)fisheragservice(#)com/tm/users(#)html
Please replace the (#)'s with .'s because the page contans actual email addresses I rather not have a spma bot find..

Can't you just attach the click event on the link instead of the img inside it and then use this?
$('#datatable tbody tr a.delete').live( 'click', function (e) {
var rowID = $(this).attr('href');
alert(rowID);
if (!fancyConfirm(rowID, "Are you sure you want to delete this record?", function(ret) { alert(rowID) }))
e.preventDefault();
});
Example link

You care selecting all the anchors using $('a') to get the rowID. That will not work. Instead use the parent().attr() function in the click handler. i.e.:
$('#datatable tbody tr a.delete img').live( 'click', function (e) {
var rowID = $(this).parent().attr('href');
alert(rowID);
if (!fancyConfirm(rowID, "Are you sure you want to delete this record?", function(ret) { alert(rowID) }))
e.preventDefault();
});

I am unsure if you are looking for the actual table row, or if the row
has some meaningful information like a database key.
if you indeed looking at a row id, consider the example below, which
uses the fnRender attribute.
var oTable = $('#inventory_list').dataTable ({
'bServerSide' : true,
'bAutoWidth' : false,
'bJQueryUI' : false,
'sPaginationType': 'full_numbers',
'sAjaxSource' : '/inventory/listall',
'aoColumns' :
[
{
'bSearchable': false,
"bSortable": false,
"fnRender" : function ( oObj )
{
var colval = '<div class="editcol"><a href="/inventory/edit/' +
oObj.aData[0] + '">' +
'<img src="/img/edit.png" alt="edit"><a/>' +
'<a href="/inventory/delete/' + oObj.aData[0] + '">' +
'<img src="/img/delete.png" alt="delete"><a/>' +
'</div>';
return colval;
}
},
null,
null,
null,
null,
null,
null,
null,
null,
null
]
});
The first column (out of 10) contains the edit/delete icons.
The listall call to the server return the inventory id in the first
cell, which is referenced by oObj.aData[0], ans used to build the URL.

Related

Materialize CSS on chip delete

I have been trying to get the tag of a deleted chip from the div in the Materialize chips class, but nothing is working.
Here is what I have already tried.
$('.chips').on('chip.delete', function(e, chip){
console.log(chip);
console.log(e);
console.log(chip.tag);
});
None of the above is working.
With just only console.log(chip), I get undefined error in JavaScript console, but the function is firing when I delete the chip. I am just not able to get the value of tag of deleted chip. I want to store the tag in a variable.
I am creating chips dynamically on Materialize date select:
$('#pm_date').change(function () {
var chipvalue = $(this).val();
if (chipvalue !== "") {
// checking if tag already exits
if ($("#date_chip_select:contains(" + chipvalue + ")").length > 0) {
alert('Date already selected');
} else {
var appendstring = "<div class='chip' id='date_chip_child_" + chip_id + "'>" + chipvalue + "<i class='material-icons close'>close</i></div>";
}
}
});
Here is the fiddle: https://jsfiddle.net/hq22mne4/1/
chips.js, which is part of materialize, doesn't seem to expose any methods for adding or removing chips programmatically. It seems to exclusively listen for an enter keydown event and then internally add the chip.
So, I stitched together a workaround that does just that. I set potential chip's value within your onchange event:
$("#datechips").find('input').val($(this).val());
And create the chip when date picker is closed:
$('.datepicker').pickadate({
selectMonths: true,
selectYears: 15,
onClose: function() {
// add chip via filling the input and simulating enter
$("#datechips").find('input').trigger({ type : 'keydown', which : 13 });
},
});
It may not be ideal, but you should be able to tailor this going forward.
https://jsfiddle.net/j3ej8240/
I've also had a lot of trouble working this out. This is how I capture the add and delete chip events without using jQuery:
function chipDeleted(e, data) {
console.log("Chip was deleted with text: " + data.childNodes[0].textContent);
}
function chipAdded(e, data) {
console.log("Chip was added with text: " + data.childNodes[0].textContent);
}
//
document.addEventListener("DOMContentLoaded", function (e) {
console.log("DOM fully loaded and parsed");
var firstTag = "Initial Tag";
var elems = document.querySelectorAll('.chips');
var instances = M.Chips.init(elems, {
data:[{
tag: firstTag
}],
autocompleteOptions: {
limit: Infinity,
minLength: 1
},
placeholder: "No search...",
onChipDelete: function (e, data) { chipDeleted(e, data) },
onChipAdd: function (e, data) { chipAdded(e, data) }
});
});
And my HTML part is like this:
<body>
<div class="chips search-history"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script>
</body>

Button click in kendo grid column firing onclick of whole row

Our customer wanted a kendo grid where he can click anywhere on a row to open the corresponding detail page. I'm adding the rows like this:
const cols = [
{ field: "Date", title: "Date", template: "#=kendo.toString(kendo.parseDate(Date, 'yyyy-MM-dd), 'dd.MM.yyyy')#" },
{ field: "Title", title: "Title" },
{ field: "", command: ["destroy"], title: " " }];
let grid = $("#grid").kendoGrid({
dataSource: this.dataSource,
pageable: true,
filterable: true,
sortable: true,
columns: cols,
editable: "detail"
}).data("kendoGrid");
grid.one("dataBound", this.onDataBound.bind(this));
And in my function onDataBound():
const grid = $("#grid").data("kendoGrid");
$(grid.tbody).on("click", "tr", function (e) {
const rowData = grid.dataItem(this);
const URL = startInfo.ApplicationRoot + "SomeDetailPage?SomeId=" + rowData.get("SomeId");
window.open(URL, '_blank');
});
This works perfectly as expected. However, as you see, I have a column with a delete button. Here is the problem. Whenever I click on the delete button, I'm getting the confirmation message ("Are you sure to delete [...]?") and actually can delete the row successfully, but the detail page of the row opens as soon as I click the button.
How can I let the row know that it shouldn't open the detail page when I click the delete button?
You should use e.stopPropagation(); on delete button so it will not pass the event to the row also.
I've found a solution. I can check the tagName when binding the click function to the row:
$(grid.tbody).on("click", "tr", function (e) {
if (e.target.tagName == "TD") {
const URL = startInfo.ApplicationRoot + "SomeDetailPage?SomeId=" + rowData.get("SomeId");
window.open(URL, '_blank');
}
});
When I click the button, tagName get either "SPAN" or "A". Everything outside the button results in "TD".

DataTable jquery selectors not firing

I have following code to handle clicks on row or individual cells.
$(document).ready(function() {
var JSON_URL = '{% url "technician_activity" %}';
var oTable = $('#technician_activity').dataTable( {
"processing": true,
"serverSide": true,
"ajax": JSON_URL ,
"jQueryUI": true
} );
alert("Without this alert selectors don't work? oTable = " + oTable);
oTable.$('tr').click( function () {
var data = oTable.fnGetData( this );
alert("Column " + data);
});
oTable.$('td').click( function () {
var data = oTable.fnGetData( this );
alert("Cell " + data);
});
});
One thing that puzzels me is without the first alert statement
alert("Without this alert selectors don't work? oTable = " + oTable);
selectors for tr and td don't work this is very puzzling to me -- what is the difference that this alert() is making?
I am now using code as suggested here - http://www.datatables.net/examples/server_side/select_rows.html
But it still remains question as to why the in code I initially posted, with first alert() statement things work but they don't work when that alert statement is absent....
Just for curiosity sake would like to understand whats going on there in case someone has ideas.

link is not working in IE8

i am using the jquery for developing my system.
for particular functionality i am sending link through json data to have link for each row
of jqgrid table.
as
"<a href='#' class='ui-icon ui-icon-pencil' onclick='EditClick(\"" + {MYPRIMARY KEY}+ "\");return false;'>Edit</a>"
in javasript i have function as
function EditClick(param)
{
$('#mainDiv').load('/contoller/action/' + param, function() {
});
return false;
}
here action returns the view().
in this EditClick function i am loading another page in my main div.
This runs on IE7,firefox smoothly,but using it on IE8 sometimes its works sometimes not.
i mean sometime required page loads in main div sometimes not.
i realy dont understand the problem.
please guide me through this.
thank you.
I had a few problems working with jgGrid events a row.
What I did was to add a custom button:
jQuery("myGrid").navGrid('#myPager', { edit: false, add: false, del: false, search: false }, {}, {}, {})
.navButtonAdd('#myPager', { caption: "Do something", buttonicon: "ui-icon-note",
onClickButton: function() { var rowid = jQuery("myGrid").jqGrid('getGridParam', 'selrow');
if ((rowid == null) || (rowid == 0)) {
alert("Select a row before!"); }
else {
EditClick(rowid);
}
}, position: "last" })
As you can see the function EditClick is triggered only if you've selected one row in the grid. rowid should be your primary key.
Hope it helps.

Is it possible to search through json result with jQuery

What I'm trying to achieve, is to output a json list that contains a list of Css classes, and their corresponding url records, i.e.
var jsonList = [{
"CSSClass": "testclass1",
"VideoUrl": "/Movies/movie.flv"
}, {
"CSSClass": "testclass2",
"VideoUrl": "/Movies/movie2.flx"
}]; //]]>
foreach item in the list I am adding a click event to the class...
$.each(script, function() {
$("." + this.CSSClass, "#pageContainer").live('click', function(e) {
videoPlayer.playMovie(this);
return false;
});
});
What I'm wondering, is if I can somehow get the corresponding url from the jsonlist, without having to loop through them all again, searching for CSSClass, or adding the url to the link as an attribute?
you can add an Index and an Item parameter to the callback function in $.each method.
$.each(script, function(i, item) {
$("." + item.CSSClass, "#pageConainer").live("click", function() {
videoPlayer.playMovie(item.VideoUrl);
return false;
});
});
"i" will be a counter of each iteration within the json object
"item" will represent the object in use
Absolutely, you just need to capture the your object so that the click function's closure has access to the right thing when it fires. Something like this should work:
$.each(script, function() {
var vid = this;
$("." + vid.CSSClass, "#pageContainer").live('click', function(e) {
videoPlayer.playMovie(vid.VideoUrl);
return false;
});
});

Categories