writing to tr td with onClick() - javascript

I am trying to get an onClick function to highlight a table row (within a dynamicTable) and also write "test read" to the clicked td[0] within this row.
this is what i have (found and tweaked from the net / stackOverflow)
$("#dynamicTable tr").click(function() {
var selected = $(this).hasClass("highlight_tr");
$("#dynamicTable tr").removeClass("highlight_tr");
if(!selected)
$(this).addClass("highlight_tr");
});
try{
$('#dynamicTable').dataTable({
"bPaginate": true,
"sPaginationType": "full_numbers",
"bLengthChange": true,
"bFilter": true,
"bSort": true,
"bInfo": true,
"bAutoWidth": true,
"sCookiePrefix": "my_datatable_",
"aaSorting": [[ 2, "desc" ]],
"aoColumns": [
{ "sType": "html" },
{ "sType": "html" },
{ "sType": "string" },
{ "sType": "html" },
{ "sType": "html" },
null
]
});
} catch (e){
errorMessage(e);
}
this works fine with highlighting the row and of course the dynamicTable
i can not work out what to add in order to get add HTML to the table cell though
i have tried as a test
$(this).innerHTML("test read");
thinking this will write to the full row, but it does nothing.
I have also tried a few other things but none work down to my lack of javaScript knowledge...
I am not very good with javaScript as you can see..., but can usually cobble something together with help from the net, but this one is making my head ache. Any help is greatly appreciated!

jQuery does not have an innerHTML method, this is a property of native DOM nodes, not jQuery collections.
Perhaps you mean something like this?
this.innerHTML = "test read";
The jQuery equivalent of this is the html method.
$(this).html("test read");
However, if you want only plain text, and not HTML, you should use the text method.
$(this).text("test read");
For completeness, the native DOM node equivalent for plain text would be textContent.
this.textContent = "test read";

You cannot write directly inside tr element but write in td:
$(this).find('td:eq(0)').text("test read");//writes text in first td
If you want to write in all td of the tr then just remove eq() method.
You can always see the documentation like eq, text, html

or try
$("td:first").text("test read");
--

Related

Custom pasting into empty datatable

When I'm trying to paste into the empty area within the webix datatable, nothing happens and onPaste event doesn't occur.
Basically, I want to add a new item through onPaste even when existing data items aren't selected. But whether it's possible?
Something like the 'insert' operation in a list, but in my use-case the datatable can be empty after init (in the following sample I've added an item to make clipboard work). Here it is:
http://webix.com/snippet/9ae6635b
webix.ui({
id:'grid',
view:'datatable',
select:true,
clipboard:'custom',
editable:true,
columns:[
{ id:'id' },
{ id:'name', fillspace:true, editor:"text" },
{ id:'details' }
],
data: [
{ }
],
on:{
onPaste: function(text){
this.add({ id:webix.uid(), name:text })
}
}
});
Any suggestions are appreciated.
I found that 'clipbuffer' has focus only when datatable has the selection. Most probably it is required for data editing, detecting position or whatever. Anyway, the 'clipbuffer' can be focused manually:
var clipEvent = webix.event($$("grid").getNode(), "click", function(){
webix.clipbuffer.focus();
});
Sample: http://webix.com/snippet/aa441e70

How to dynamically enable/disable Responsive extension

I have a project where users need to be able to select whether or not the accompanying script activates Responsive extension of jQuery DataTables.
I want to add a dropdown menu in HTML that lets users choose whether option responsive is set to true or false in dataTable() initialization options.
I tried to add a separate function to select the value and used a global variable to get it to the dataTable() function but couldn't get that to work.
JavaScript:
$(document).ready(function(){
$("#example").dataTable({
"responsive": false,
"processing": false,
"serverSide": true,
"ajax": "scripts/university.php",
"columns": [
// ID
null, ........
*HTML**
<select id="selected2" onchange="myFunction()">
<option value="true">true</option>
<option value="false">false</option>
</select>
I tried adding a document.getElementById clause as the first line in the dataTable function but couldn't make it work.
What can I add to the existing function to make responsive option user selectable from the list on the HTML page?
SOLUTION
You need to destroy table to re-initialize it and enable/disable Responsive extension.
var dtOptions = {
responsive: true
};
var table = $('#example').DataTable(dtOptions);
$('#ctrl-select').on('change', function(){
dtOptions.responsive = ($(this).val() === "1") ? true : false;
$('#example').DataTable().destroy();
$('#example').removeClass('dtr-inline collapsed');
table = $('#example').DataTable(dtOptions);
});
NOTES
When the table is destroyed, Responsive extension leaves some classes (dtr-inline, collapsed), so I remove them manually before initializing the table again.
Also I suggest having all options in a separate object dtOptions to make re-initialization easier, that way you just need to toggle one option responsive.
DEMO
See this jsFiddle for code and demonstration.
Assuming that it is this DataTable plug-in then you can change the responsive setting in your myFunction. First,
var table = $('#example').DataTable(/* your current settings */);
then, in myFunction,
new $.fn.dataTable.Responsive( table, {
details: true
} );
Have you tried using an onChange event handler to get the value whenever there is a change in the dropdown selection? I would think using the onChange to toggle a variable value and assigning it to whichever dataTable key would work. Like so:
$(document).ready(function(){
var selected;
$('#selected2').onChange( function() {
selected = $(this).val();
}
$("#example").dataTable({
"responsive": false,
"processing": selected,
"serverSide": true,
"ajax": "scripts/university.php",
"columns": [
// ID
null, ........
JSFiddle
Well get rid of the obtrusive javascript or use it ( onchange="myFunction()")
$(document).ready(function(){
var selectedValue;
$('#selected2').change( function() {
selectedValue = $(this).val();
alert(selectedValue);
});
});

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

JQuery DataTables: Show/hide row details with multiple tables

I'm aware there's a similar question on here JQuery DataTables: How to show/hide row details with multiple tables? but that doesn't apply to my current problem completely.
I have the code:
var oTable = $('.dataTable').dataTable( {
"aoColumnDefs": [
{ "bSortable": false, "aTargets": [ 0,3,4 ] },
{ "bVisible": false, "aTargets": [ 4 ] }
],
"aoColumns": [
null,
null,
null,
null,
{ "sType": "html" }
],
"aaSorting": [[1, 'asc']],
"bFilter": false,
"bPaginate": false,
"fnInitComplete": function(oSettings) {
/* Add event listener for opening and closing details
* Note that the indicator for showing which row is open is not controlled by DataTables,
* rather it is done here
*/
$('.dataTable tbody td img').live('click', function () {
var nTr = this.parentNode.parentNode;
if (oTable.fnIsOpen(nTr)) {
// This row is already open - close it
this.src = "css/images/details_open.png";
oTable.fnClose(nTr);
} else {
// Open this row
this.src = "css/images/details_close.png";
oTable.fnOpen(nTr, fnFormatDetails(oTable, nTr), 'details');
}
} );
}
});
That works if there's only one if I add the dataTable class to a second table, then they work as datatables but the show/hide buttons fail in both tables. Both tables have the same count of fields and content, just for the sake of making it work, but still no success.
On the similar post, the person suggests adding:
tbl = $(this).parent().parent().dataTable();
to the click function but I have tried that and it didn't work.
What am I missing??
In short: get rid of the fnInitComplete, and move the "live" call to below the dataTable call.
As an example, if you have three tables, after each table is completed, your current code will execute the fnInitComplete method - so fnInitComplete gets called 3 times. Your fnInitComplete uses a selector to "live" the click event to an img, and the selector will "live" to all tables. This results in multiple bindings. See this jsfiddle, http://jsfiddle.net/KeVwJ/, which duplicates your method. (Note that I'm not using images so only capturing click on the td cell, not an image).
var oTable = $('.dataTable').dataTable( {
"bFilter": false,
"bPaginate": false,
"fnInitComplete": function(oSettings) {
$('.dataTable tbody td').live('click', function () {
var nTr = this.parentNode;
alert(nTr);
} );
}
});
If you click on any row in the table, you will get 3 alert boxes, because 3 tables are created and they each "live" click for all tables at fnInitComplete.
To fix, remove the fnInitComplete, and put the code for "live" after the call to dataTable. That should solve it. See this jsfiddle: http://jsfiddle.net/rgMNu/ Click on any row in the table and it will identify the correct table class. Again since I am capturing the click on td, I only have to do this.parentNode.parentNode.parentNode. I think you'll have to do another level.
$('.dataTable tbody td').live('click', function ()
{
var t = this.parentNode.parentNode.parentNode;
alert(jQuery(t).attr('class'));
} );

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