jQuery Datatable access row data ( render parameter ) on jQuery click event - javascript

I have created link in datatable as:
$('#example').dataTable( {
"columnDefs": [ {
"targets": 1,
"render": function ( data, type, full, meta ) {
return 'Download';
}
} ]
} );
I can access id on clicking <a> tag using jQuery click event, but I have several fields to access. And I don't want to use data- attribute to access each field.
How can I access row object i.e.(full) , in jQuery event ?
What I have tried is:
"render": function ( data, type, full, meta ) {
alert(full);
return 'Download';
}
In jQuery event alert( $(this).data('full') ); I can see only [Object object].
I have tried to convert it to String but no success.

Use row().data() API method to get data for any given row.
For example:
$('#example').on('click', 'tbody a', function(){
var $tr = $(this).closest('tr');
var data = table.row($tr).data();
console.log(data);
});
See this example for code and demonstration.

Try jquery .data() to set / get data
$(your_component).data("full", full)
or
JSON.stringify(full) // convert json to string

Related

Datatables select row programmatically without triggering select event

In Datatable's Select plugin, there is a way to programmatically select a row:
https://datatables.net/reference/api/row().select()
But this will also trigger the row's select event, which is not ideal in my context as it will get into an infinite loop...
Is there a way of doing this without having to use some control variable?
The bit in their API for the select function is as follows :
apiRegisterPlural( 'rows().select()', 'row().select()', function ( select ) {
var api = this;
if ( select === false ) {
return this.deselect();
}
this.iterator( 'row', function ( ctx, idx ) {
clear( ctx );
ctx.aoData[ idx ]._select_selected = true;
$( ctx.aoData[ idx ].nTr ).addClass( ctx._select.className );
} );
this.iterator( 'table', function ( ctx, i ) {
eventTrigger( api, 'select', [ 'row', api[i] ], true );
} );
return this;
} );
It seems I just need to figure out the ctx.aoData[ idx ]._select_selected = true; part, is ctx the row object? I'm clueless.
I know this question is very old, but for those coming here later on might like an answer.
Datatables has a select event and a user-select event.
Just use the user-select event where applicable and leave the select event for all other purposes.
https://datatables.net/reference/event/user-select
For example,
var table = $('#example').DataTable( {
select: true
} );
table
.on( 'user-select', function ( e, dt, type, cell, originalEvent ) {
if ( originalEvent.target.nodeName.toLowerCase() === 'img' ) {
e.preventDefault();
}
} );
Update : Just to add an additional choice since the user-select event does fire even on a deselect. One way to avoid some issues I think many people have is when the table is initialized they programmatically select items. You can avoid this trigger by simply enabling your select and deselect events only after the table has been initialized.
Datatables has an initComplete event. So do it like so. Where table is a variable to your datatable reference.
initComplete: function(settings, json) {
table.on('select', function( e, dt, type, indexes ) {
});
}

Trying to make an event depend on another event and data is passed along using jquery custom events

for this problem I want to pass along data depending if a checkbox is checked. the data comes from the .on() second paramater.
I want to do something like this. I know it is really messed up. Im not sure how the data work and when to use .trigger()
$(document).on('justData', function(e, data){
console.log(data);
})
$('.justData').on('click', function(){
var insert
dataobj ={
"mike" : 'mikevalue',
"john" : 'johnValue'
}
$("#checkThis").on('change', function(e, data){
if(this.checked){
insert = dataobj.mike
}else{
insert = dataobj.john
}
})
$(this).trigger('justData', insert)
})
I wanted to insert "mikevalue" if the box is checked and "johnvalue" if unchecked.
I'm learning how to use mediators. I think that's when you do $emitter = $({}) so I want to separate event. when the user clicks on the $(.justData) i would have $({}).trigger("Ischecked") something like that I'm confused. If some one can show me how to pass along dynamic data to different events using $emitter .trigger() .on() that would be great.
You're on the right track. This is the simple and clear example given from the jQuery API Docs for handling custom events:
$( "#foo" ).on( "custom", function( event, param1, param2 ) {
alert( param1 + "\n" + param2 );
});
$( "#foo").trigger( "custom", [ "Custom", "Event" ] );
Also cleaned up your code a little bit:
$('body').on('justData', function(e, data){
console.log(data);
});
$('.justData').on('click', function(e){
var insert = "",
$checkbox = $('#checkThis'),
data = {
"mike" : 'mikevalue',
"john" : 'johnValue'
};
if($checkbox.prop('checked')){
insert = data.mike;
} else {
insert = data.john;
}
$('body').trigger('justData', insert);
});

jQuery DataTables - add jquery generated element with events to a table cell

I'm using jQuery DataTables ( http://www.datatables.net ) to generate a table. I want to insert in certain cells(from a column) a jquery generated html element witch has some events attached to it. (onClick for example).
I was thinking about mRender but I found that I need to return a string instead of an object.
here is the code:
table.dataTable({
"aoColumns": [{
"mRender":function() {
var element=$("<div></div>").on("click",function(){
alert("do something");
});
return element;
}
},
{"sWidth": "350px"}]
});
The code is not working because what I see rendered is
[Object]
I can get the html code of the element using jQuery.html() but then I will loose the events attached to the element.
Is there any solution? Is this a design flaw in DataTables or am I missing something?
You can insert placeholder elements via mRender or sDefaultContent and add the actual content and events during the fnRowCallback events. Something like this:
table.dataTable({
"aoColumns": [{
"sDefaultContent": '<div class="stuff"></div>'
"sWidth": "350px"
}],
"fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
var element = $(nRow).find("div.stuff");
// do stuff
element.on("click",function() {
alert("do something on row: " + iDisplayIndex);
});
}
});

How do I store 2 parameters with JQuery.data()

I have the following js:
$('.overview_table_header').click(function() {
header = $(this)
$.get("/sort", { col: $.trim($(this).text()), sort: header.data('sort') },
function(data) {
$('#pages').html(data.html);
header.data('sort', data.sort);
}
);
});
Which passes 2 parameters (A get request to /sort): {"col"=>"DATA", "sort"=>"OTHERDATA"}
I'm new to JQuery and Ajax. How do I store The above DATA and OTHERDATA in a hidden field tag within my html? Is using JQuery.data() the best method to accomplish this task?
.data() is what I would use. You can do:
$(header).data({"col":"DATA", "sort":"OTHERDATA"});
or
$(header).data("col","DATA");
$(header).data("sort","OTHERDATA");

JQuery DataTable Cell from a row click

I am trying to implement a function on jquery datatable, that returns the 1st and the 4th column of a clicked row
i am following this example, which allows me to manipulate a clicked row
http://datatables.net/examples/api/select_single_row.html
thinking that i can change this handler to do the read cell value procedures and use the value on my own logic
/* Add a click handler to the rows - this could be used as a callback */
$("#example tbody").click(function(event) {
$(oTable.fnSettings().aoData).each(function (){
$(this.nTr).removeClass('row_selected');
});
$(event.target.parentNode).addClass('row_selected');
});
i have also come over with this little code segment from dataTable forum http://datatables.net/forums/comments.php?DiscussionID=1384&page=1#Item_0
$('#example tbody tr').click( function () {
// Alert the contents of an element in a SPAN in the first TD
alert( $('td:eq(0) span', this).html() );
} );
may i have any pointer so i can get the 1st and 4th column of the clicked field?
next part
I have the above solved, thanks nick
however i have the next part of the problem. when i init the table
i use
/* Init the table */
oTable = $('#filetable').dataTable( {
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "/crvWeb/jsonFileList.do",
"fnServerData": function ( sSource, aoData, fnCallback ) {
$.ajax( {
"dataType": 'json',
"type": "POST",
"url": sSource,
"data": aoData,
"success": fnCallback
} );
}
} );
my servlet takes a dir request parameter and returns a listing to the datatable as json response.
/crvWeb/jsonFileList.do
how can i add and get serlvet response with post request so i can have my table updated?
You can use .delegate() easiest here, like this:
$("#example tbody").delegate("tr", "click", function() {
var firstCellText = $("td:first", this).text();
var fourthCellText = $("td:eq(3)", this).text();
});
You can try out a demo here
With .delegate() this refers to the <tr> since that's the click we're handling, making things quite a bit cleaner..and it's still only one event handler at the <tbody> level, not one per <tr>.
This should do the trick, if I'm reading your code correctly:
$("tr.row_selected td:nth-child(1), tr.row_selected td:nth-child(4)");
It should return the first and fourth child of all tr elements with the class row_selected.

Categories