Datatables child rows form - javascript

I am using this example but within the child rows, I have a form. The problem is, it's not submitting the input from the child rows if the child rows are closed. Now I see datatables is using: show() and hide() functions as in this code of their example:
if ( row.child.isShown() ) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row
row.child( format(row.data()) ).show();
tr.addClass('shown');
}
Now that makes me think it's just hiding it and showing it so when its hidden, it should still be there AND submitted, but it isn't since they are probably using a datatables made function or something. How would I make it that I can actually submit the input fields in the child rows when the child rows are "hidden"? It works fine when I have the row opened.

Unfortunately JQuery DataTables doesn't provide any method to get the informations that you need, moreover it removes the hided rows from the DOM.
So, the only thing you could do is to store the modified values in detail rows in some variable and read them on submit, see following please:
var dataSet = [
{
"id" : 1,
"name" : "Tiger Nixon",
"position" : "Edinburgh",
"salary" : "5421"
},
{
"id" : 2,
"name" : "Ludovico Moro",
"position" : "Milan",
"salary" : "8670"
},
{
"id" : 3,
"name" : "Julio Iglesias",
"position" : "Madrid",
"salary" : "12500"
}
];
var fullnames = [];
$(document).ready(function() {
var table = $('#example').DataTable( {
"data": dataSet,
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "name" },
{ "data": "position" },
{ "data": "salary" }
],
"order": [[1, 'asc']]
} );
// Add event listener for opening and closing details
$('#example tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = table.row( tr );
if ( row.child.isShown() ) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row
row.child( format(row.data()) ).show();
tr.addClass('shown');
}
} );
} );
function format ( d ) {
// `d` is the original data object for the row
return '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">'+
'<tr>'+
'<td>Full name:</td>'+
'<td><input type="text" class="fullname" id="' + d.id + '" value="' + d.name + '" onchange="javascript:inputChange(this.id, this.value)"></td>'+
'</tr>'+
'</table>';
}
$("#form1").submit(function( event ) {
$.each(fullnames, function(index, value){
if(fullnames[index]){
console.log("Modified record " + index + ", new value is: " + value);
}
});
event.preventDefault();
});
function inputChange(id, val){
fullnames[id] = val;
}
td.details-control {
background: url('https://datatables.net/examples/resources/details_open.png') no-repeat center center;
cursor: pointer;
}
tr.shown td.details-control {
background: url('https://datatables.net/examples/resources/details_close.png') no-repeat center center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.6/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.6/css/jquery.dataTables.min.css" rel="stylesheet"/>
<form id="form1">
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Position</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th></th>
<th>Name</th>
<th>Position</th>
<th>Salary</th>
</tr>
</tfoot>
</table>
<input type="submit">
</form>
To sum up:
1) Declare a global var to store the fullnames
var fullnames = [];
2) In the function format, add onchange listener to the input box
onchange="javascript:inputChange(this.id, this.value)"
3) Create the listener
function inputChange(id, val){
fullnames[id] = val;
}
4) Finally, read its values on submit
$.each(fullnames, function(index, value){
if(fullnames[index]){
console.log("Modified record " + index + ", new value is: " + value);
}
});
Obviously instead of a fullnames array you can save an array of objects containing all the fields you need.
I hope it helps you, bye.

Related

Javascript inserting data into cell with index and data

This seems very simple but I just can't get my head around it. I am trying to insert data I get back and replace the cell contents at the specified cell index. I am getting the data (Kevin) and index (0) back from the function call's input parameters. But I'm just not able to insert this data into the desired cell. I have tried insertCell function, but this won't replace the contents, it'll just keep appending new cells.
My console.logs report the correct index and data, I've tried inserting/replacing the content of the cell like this: td[index].innerHTML = data but this gives an error, apparently td[index] returns a object HTMLTableCellElement, so i can't do it this way.
HTML:
<table>
...
<tbody>
<tr id="data-row-body">
<td></td> //need to insert here
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
Javscript:
function exeAPI(api, key, index, callback) {
$.ajax({
url:"../lib/getData.php",
type: "POST",
data: {
name: name,
api: api
},
dataType: "text",
success:function(result){
console.log(result);
if(result){
try {
var jsonText = result.substr(result.indexOf('{'));
console.log("this is the jsontext: " + jsonText);
var jsonObj = JSON.parse(jsonText);
callback(jsonObj.response.result[key], index);
} catch(e) {
console.log(e);
alert("Error getting rack data!");
}
}
}
});
//getting back "Kevin" and "0" as parameters to insert here
function exeAPIcallback(data, index){
var td = $('#data-table tbody td');
var tr = $('#data-table tbody tr');
var row = document.getElementById("data-row-body");
console.log("This is the cell index: " + th[index].innerHTML + " ,index: " + th[index]);
console.log("This is the cell index: " + td[index]);
td[index].innerHTML = data; // this doesn't work
}
function popupParamChecker(){
exeAPI("getData.php", "Kevin", 0, exeAPIcallback);
$("#dialog-params").dialog({
resizable: false,
width: 1000,
modal: true,
draggable: false,
buttons: {
Confirm: function() {
$( this ).dialog( "close" );
}
}
});
}
Is there an easier way of doing this?
The count of row may be many, so I added one param for your APICallback.
Below is the codes:
1. First select our all rows under the table by $('table tbody tr')
2. use .eq(index) to get the specific row
3. .find() all tds then get the specific cell to change the text.
function exeAPIcallback1(data, row, col){
let td = $('table tbody tr').eq(row).find('td').eq(col);
td.text(td.text()+data)
}
function exeAPIcallback2(data, row, col){
$('table tbody tr').eq(row).find('td').eq(col).text(data);
}
table td{
width:10px;
height:10px;
border:1px;
background-color:yellow;
}
table td:nth-child(even){
background-color:red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="exeAPIcallback1('test',0,0)"> Test Insert</button>
<button onclick="exeAPIcallback2('test',0,0)"> Test Replace</button>
<table>
<tbody>
<tr id="data-row-body">
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
Use the following function to add content to a table cell.
function add_content_to_cell(table_selector, row_number, cell_number, content) {
$(table_selector).find('tr')
.eq(row_number-1).find('td').eq(cell_number-1)
.append(content);
}
Simply choose the table id, the row number, the cell number and the content you wish to add.
Usage:
add_content_to_cell('#my_table', 2, 5, "I am some content")
Result:
With jQuery:
$('#data-row-body').find('td').eq(index).text(data); /* strips down html, if any */
OR
$('#data-row-body').find('td').eq(index).html(data); /* with html tags */
See if this works, with your current snippet
change
var td = $('#data-table tbody td');
to
var td = $('#data-row-body').children('td');
$(td[index]).html(data);
here, assuming that index is always within the bounds of

dynamic tooltip text on every cell of table

i can set tool-tip for each cell of my table using title
but is there a way to make the tool-tip text to be dynamic ?
for example when i hover on any cell of table it show information about that cells entire row.
<td title="something">46879</td>
example using datatables plugin :
$(document).ready(function() {
$('#example tbody tr').each( function() {
var sTitle;
var nTds = $('td', this);
var sBrowser = $(nTds[1]).text();
var sGrade = $(nTds[4]).text();
if ( sGrade == "A" )
sTitle = sBrowser+' will provide a first class (A) level of CSS
support.';
else if ( sGrade == "C" )
sTitle = sBrowser+' will provide a core (C) level of CSS support.';
else if ( sGrade == "X" )
sTitle = sBrowser+' does not provide CSS support or has a broken
implementation. Block CSS.';
else
sTitle = sBrowser+' will provide an undefined level of CSS
support.';
this.setAttribute( 'title', sTitle );
} );
var oTable = $('#example').dataTable();
$( oTable.fnGetNodes() ).tooltip( {
"delay": 0,
"track": true,
"fade": 250
} );
} );
this is what i mean :
https://jsfiddle.net/pow7651t/1/
Please have a look at following solution. Note that, I have added an extra variable for columns. Let me know if this works, or if there is any issue with this solution.
$(document).ready(function() {
var columns = ['Names', 'Reg Number', 'ID Code']
$('#example tbody tr').each(function() {
var cells = $('td', this);
var titleArr = cells.map(function(index) {
return columns[index] + '=' + this.innerHTML;
});
cells.each(function(index) {
var finalTooltip = titleArr.filter(function(i){
return index !== i;
});
$(this).attr('title', finalTooltip.toArray().join(','))
})
var name = cells[0];
var regNumber = cells[1];
var idCode = cells[2];
});
var oTable = $('#example').dataTable();
$(oTable.fnGetNodes()).tooltip({
"delay": 0,
"track": true,
"fade": 250
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet"/>
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet"/>
<table id="example">
<thead>
<th>Names</th>
<th>RegNumber</th>
<th>ID Code</th>
</thead>
<tbody>
<tr>
<td>Ryan</td>
<td>49765</td>
<td>34</td>
</tr>
<tr>
<td>John</td>
<td>58964</td>
<td>42</td>
</tr>
<tr>
<td>Daniel</td>
<td>472658</td>
<td>24</td>
</tr>
</tbody>
</table>
You have to create a title attr for each cell of your table ,
in the below Fiddle a did loop throw each row , and inside those a get the text and the header of each cell except the current cell (.not(this)) and then set the title attribute to this last .
See this Fiddle

How to make a jQuery table editable for specific column only

The code I have is below using a simple DataTable . I get the data and all sorting is great but now I want to update the cell contents in last column only which is the "reason not covered" column and submit it back as update to DB possibly by AJAX calls . I am not sure whether to use Editor or JEditable to make the table editable and how to make it editable for that column alone . Have tried different options using makeEditable and Editor but cannot make the inline cell contents editable for column or cell .Have dataTables.editor.min.js in the script path. Also tried jEditable with jquery.jeditable.mini.js Any help deeply appreciated.
jquery-3.1.1.min.js, jquery.dataTables.min.js, dataTables.buttons.min.js, buttons.colVis.min.js, dataTables.editor.min.js
<script>
$(document).ready(function() {
$('#selectedDetails').DataTable({
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"fixedHeader": true,
"scrollY": '400px'
});
} );</script>
<table id = "selectedDetails" class="table table-striped table-bordered" cellspacing="0" width="80%">
<caption><h3>DETAILS FOR SELECTED FILTERS: <font color="brown">FORM ID</font>=<font color="blue"><%=request.getAttribute("formNameSelection")%></font> AND <font color="brown">COVERED IN AUTOTAX</font> = <font color="blue"><%=request.getAttribute("YesOrNoValueSelection") %></font> </h3></caption>
<thead style="background-color:#D7DBDD; border:solid 2px; border-color:black">
<tr>
<th>FORM ID</th>
<th>FIELD ID</th>
<th>FIELD NAME</th>
<th>FIELD TYPE</th>
<th>NO: OF HARD CALCS</th>
<th>NO: OF DROP ASSIGNEDS</th>
<th>COVERED IN AUTOTAX ?</th>
<th>REASON NOT COVERED</th>
</tr>
<thead>
</thead>
<tbody>
<c:forEach var="filterFieldInfo" items="${filteredValues}">
<tr>
<td style="width: 45px;text-align: center;" align="center"><c:out value="${filterFieldInfo.formId}" /></td>
<td style="width: 45px;text-align: center;" align="center"><c:out value="${filterFieldInfo.fieldId}" /></td>
<td style="width: 45px;text-align: center;" align="center"><c:out value="${filterFieldInfo.fieldName}" /></td>
<td style="width: 45px;text-align: center;" align="center"><c:out value="${filterFieldInfo.fieldType}" /></td>
<td style="width: 45px;text-align: center;" align="center"><c:out value="${filterFieldInfo.numHardCalcs}" /></td>
<td style="width: 45px;text-align: center;" align="center"><c:out value="${filterFieldInfo.numDroptAssigneds}" /></td>
<td style="width: 45px;text-align: center;" align="center"><c:out value="${filterFieldInfo.autoTaxCovered}" /></td>
<td style="width: 45px;text-align: center;" align="center"><c:out value="${filterFieldInfo.reasonAutoTaxCovered}" /></td>
</tr>
</c:forEach>
</tbody>
</table>
I made one more. This one, the html is created server side.
Also, it uses a pop over to allow the user to enter in the changes that way.
Like I said, I do not have access to the DataTable Editor library so I used the QTip2 (http://qtip2.com/) library instead.
Click on any cell in the office column.
http://jsbin.com/datecoy/edit?js,output
// Table defintion
$(document).ready(function () {
var dtTable = $('#example').DataTable({
columns: [{ title: "Name" }, { title: "Postition" }, { title: 'Office' }, { title: "Age" }, { title: "Start Date" }, { title: "Salary" }],
columnDefs: [{ targets: [2], className: "editColumn" }]
});
$('#example').on("click", ".editColumn", function () {
var index = $(this).index();
var cols = dtTable.settings()[0].aoColumns;
var colTitle = cols[index].title;
var data = dtTable.rows($(this).closest("tr")).data()[0];
DataTableDialog(this, colTitle, data[2]);
})
});
Here is a very simple one but not my first choice. Because it is content editable, you loose control of the width of the column and end up with some strange looking stuff.
Just click on a cell in the edit column and start typing.
event handlers keep the data object and the table cell in sync.
http://jsbin.com/zizepoh/edit?html,js,output
$(document).ready(function() {
// add editable column data
var dtData = $.map(dataStore.data, function(item){item.contentEdit = ""; return item;});
var dtTable = $('#example').DataTable( {
"data": dtData,
"select":"single",
"columnDefs":[{"targets":[6], render : function(ditem){return "<div contenteditable>" + ditem + "</div>";}}],
"columns": [
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "extn" },
{ "data": "start_date" },
{ "data": "salary" },
{"data":"contentEdit", "className": "contentEdit"}
],
dom: 'Bfrtip',
buttons: [ 'excelHtml5' ]
});
// Uses key press event handler to keep the associated data object in sync
$("#example").on("keypress", ".contentEdit div", function (){
var rData = dtTable.rows($(this).closest("tr")).data()[0];
rData.contentEdit = $(this).text();
$("#txtFollower").val($(this).text());
});
});
this one is a tad safer and more obvious. it puts in a textbox.
Also, I had to add a bit more to make the excel dump work.
http://jsbin.com/zufesop/3/edit?html,js,output
$(document).ready(function() {
// add editable column data
var dtData = $.map(dataStore.data, function(item){item.contentEdit = ""; return item;});
var dtTable = $('#example').DataTable( {
"data": dtData,
"select":"single",
"columnDefs":[{"targets":[6], render : function(ditem){return "<input type='text' value = '" + ditem +"'/>" ;}}],
"columns": [
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "extn" },
{ "data": "start_date" },
{ "data": "salary" },
{"data":"contentEdit", "className": ""}
],
dom: 'Bfrtip',
buttons: [
{
extend: 'excelHtml5',
text: 'Save as Excel',
// updates the data before being sent to excel
customizeData: function (a, b, c, d) {
var exd = a.body;
var dtdata = $('#example').DataTable().rows().data();
for (var ii = 0; ii < dtdata.length ; ++ii) {
var cur = dtdata[ii].contentEdit;
exd[ii][6] = cur;
}
}
}
]
});
// Uses key press event handler to keep the associated data object in sync
$("#example").on("keyup", "input[type='text']", function (){
var rData = dtTable.rows($(this).closest("tr")).data()[0];
rData.contentEdit = $(this).val();
$("#txtFollower").val($(this).val());
});
});
Here is something for you to look at.
All of my tables are made from an array data objects in JavaScript. Yours, I think, was made from an html table generated server side.
So, to closer emulate what you are doing I created a table server side and then tried to use my code to update it. It did not work. Below is what I had to do update it.
Basically, the code below uses an event handler that pops up an input box for the user to make the change and then save it. (I left all of that out)
// For my object array, this was all I had to do to update the data.
var dtTable = $($(target).closest("table")).DataTable();
var dtData = dtTable.rows($(target).closest("tr")).data()[0];
dtData.office = $(this).siblings("input").val();
dtTable.rows().invalidate().draw();
When I changed it to a server side table, the code above stopped working (even after changing it to work with array of arrays which server side tables use)
To get it to work, I had to update both the data object and the tables html node so it looked like this:
var columnIndex = $(target).index();
var dtTable = $($(target).closest("table")).DataTable();
var dtData = dtTable.rows($(target).closest("tr")).data()[0];
// here, I updated the data node
dtData[columnIndex] = $(this).siblings("input").val();
// then I updated the html td. Once that was done, it started working for the server side table.
$(target).html(dtData[columnIndex]);
dtTable.rows().invalidate().draw();
THanks a bunch again ! I have modified code with your example to try make it work to see what I am missing , below is the modified script and html . In your example I just needed the Edit and Save button , no functionality needed for Add and Delete. Below still doesn't work , I dont actually see even an edit button . What are the parameters inside the function function (e, dt, bt, config) signify ?
<script>
$(document).ready(function() {
var myTable = $('#selectedDetails').DataTable({
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"fixedHeader": true,
"scrollY": '400px',
buttons: [{
text: "Edit", className :"editButton",
extend: "selectedSingle",
action: function (e, dt, bt, config) { editRow(e, dt, bt, config); }
}, {
text: "Save",
extend: "selectedSingle",
action: function (e, dt, bt, config) { saveRow(e, dt, bt, config); }
}
}],
dom: "Btp",
select: "single"
});
var dataObject = myTable.rows().data();
// keep the rows from deselection when you click on a textbox
// this means you have to click between textboxes to change edit rows when more than one is open
$("#selectedDetails").on("click", "input", function (e) { e.stopPropagation(); return false; });
table.on('user-select', function (e, dt, type, cell, originalEvent) {
if ($('#selectedDetails input').length > 0) {
e.preventDefault();
return false;
}
});
});
// Save the selected row (assuming its in edit mode)
function saveRow(e, dt, bt, config) {
var r = dt.rows(".selected").nodes()[0];
// if row is not edit mode, just return.
if ($("input", r).length === 0) { return; }
var d = dt.rows(".selected").data()[0];
var containsText = false;
$(r).children("td").each(function (i, it) {
var di = $("input", it).val();
if (di.length > 0) { containsText = true; }
$(it).html(di);
d[i] = di;
});
if (!containsText) {
alert("This row contains no data and will be removed");
dt.rows(".selected").remove().draw();
}
$(".editButton span").text("Edit");
}
// Puts a row in edit mode
function editRow(e, dt, bt, config) {
var r = dt.rows(".selected").nodes()[0];
if( $("span", bt[0]).text() == "Cancel"){
if($(r).hasClass("newRow")){
dt.rows(".selected").remove().draw();
}
else {
$(r).children("td").each(function (i, it) {
var od = dt.cells(it).data();
$(it).html(od[0]);
});
}
$("span", bt[0]).text("Edit");
return;
}
// if row already in edit mode, just return.
if ($("input", r).length > 0) { return; }
$(r).children("td").each(function (i, it) {
var h = $("<input type='text'>");
h.val(it.innerText);
$(it).html(h);
});
$("span", bt[0]).text("Cancel");
}
</script>
<table id = "selectedDetails" class="table table-striped table-bordered" cellspacing="0" width="80%">
<caption><h3>DETAILS FOR SELECTED FILTERS: <font color="brown">FORM ID</font>=<font color="blue"><%=request.getAttribute("formNameSelection")%></font> AND <font color="brown">COVERED IN AUTOTAX</font> = <font color="blue"><%=request.getAttribute("YesOrNoValueSelection") %></font> </h3></caption>
<thead style="background-color:#D7DBDD; border:solid 2px; border-color:black">
<tr>
<th>FORM ID</th>
<th>FIELD ID</th>
<th>FIELD NAME</th>
<th>FIELD TYPE</th>
<th>NO: OF HARD CALCS</th>
<th>NO: OF DROP ASSIGNEDS</th>
<th>COVERED IN AUTOTAX ?</th>
<th>REASON NOT COVERED</th>
</tr>
<thead>
</thead>
<tbody>
<c:forEach var="filterFieldInfo" items="${filteredValues}">
<tr>
<td style="width: 45px;text-align: center;" align="center"><c:out value="${filterFieldInfo.formId}" /></td>
<td style="width: 45px;text-align: center;" align="center"><c:out value="${filterFieldInfo.fieldId}" /></td>
<td style="width: 45px;text-align: center;" align="center"><c:out value="${filterFieldInfo.fieldName}" /></td>
<td style="width: 45px;text-align: center;" align="center"><c:out value="${filterFieldInfo.fieldType}" /></td>
<td style="width: 45px;text-align: center;" align="center"><c:out value="${filterFieldInfo.numHardCalcs}" /></td>
<td style="width: 45px;text-align: center;" align="center"><c:out value="${filterFieldInfo.numDroptAssigneds}" /></td>
<td style="width: 45px;text-align: center;" align="center"><c:out value="${filterFieldInfo.autoTaxCovered}" /></td>
<td style="width: 45px;text-align: center;" align="center"><c:out value="${filterFieldInfo.reasonAutoTaxCovered}" /></td>
</tr>
</c:forEach>
</tbody>
</table>
contentEditable anyone?
Says it's new for HTML5, and also a "Global HTML" attribute.
Seems to work pretty well on table cells.

Javascript: loop through array of objects to find key value pair and render them in the table td

Here is the following table code created dynamically and I want to get the last 2 values stored in TD. the last td value is in the form of "key-value-pair".
I want to display something like below:
<tbody>
{{#items}}
<tr>
<td>{{name}}</td>
<td>{{description}}</td>
<td id="newval">{{new_value}}</td>
<td id="oldval">{{old_value}}</td>
</tr>
{{/items}}
</tbody>
here is the json obtained from the server:
{
"result":"OK",
"items":[
{
"name":"abc",
"description":"desc",
"new_value":{
"description":"newvalue"
},
"old_value":{
"description":"oldvalue "
}
},
{
"name":"abc3",
"description":"desc2",
"new_value":{
"interval":"newvalue2"
},
"old_value":{
"interval":"oldvalue2 "
}
}
]
}
here is the js:
$.each(lists,function(i,items){
for (var key in items) {
if(key == 'new_value'){
for(value in items[key]){
$("td#newval").html(value + " : " +items[key][value]);
}
}
}
});
Similarly I'm doing it for the old value, just replacing the "td" id and value.
but what is happening is only the first td gets updated with all the values of "new_value" in the array and the remaining td's are rendered blank.
I want to display in such a way that it will loop through the array and find the key value pair associated with the "new_value" object and render both values for the respective td's.
<td>description: newvalue</td>
<td>interval: newvalue2</td>
how can i achieve this?
Thanks!
Since Id of an element must be unique, you should use some other attribute of to group elements.
Here one possible approach is to use a class and a data attribute to specify the property to map to a field like
var data = {
"result": "OK",
"items": [{
"name": "abc",
"description": "desc",
"new_value": {
"description": "newvalue"
},
"old_value": {
"description": "oldvalue "
}
}, {
"name": "abc3",
"description": "desc2",
"new_value": {
"interval": "newvalue2"
},
"old_value": {
"interval": "oldvalue2 "
}
}]
};
var trmap = {};
$('table tr').each(function() {
trmap[$(this).children(':first-child').text().trim()] = this;
});
$.each(data.items, function(i, item) {
if (trmap[item.name]) {
var $tr = $(trmap[item.name]);
$tr.find('.val').text(function() {
var key = $(this).data('key');
var arr = [];
$.each(item[key], function(key, value) {
arr.push(key + ': ' + value)
});
return arr.join('');
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td>abc</td>
<td>desc</td>
<td class="val" data-key="new_value">key: newvalue</td>
<td class="val" data-key="old_value">key: oldvalue</td>
</tr>
<tr>
<td>abc3</td>
<td>desc2</td>
<td class="val" data-key="new_value">key: newvalue2</td>
<td class="val" data-key="old_value">key: oldvalue2</td>
</tr>
</tbody>
</table>

DataTables (JQuery) on how to multi column filter text box given a array that contain the data?

I am trying to do a multi column filter as shown in this page (http://www.datatables.net/examples/api/multi_filter.html) using a array that contain all the data (called 'my_array_data') but I could not get those filter text box displayed.
Below is the code:
<script type="text/javascript">
var asInitVals = new Array();
$(document).ready(function() {
$('#dynamic').html( '<table cellpadding="0" cellspacing="0" border="0" class="display" id="example"></table>' );
var oTable = $('#example').dataTable( {
"aaData": my_array_data,
"bProcessing": true,
"bAutoWidth": false,
"fnInitComplete": function() {
var oSettings = this.fnSettings();
for ( var i=0 ; i<oSettings.aoPreSearchCols.length ; i++ ){
if(oSettings.aoPreSearchCols[i].sSearch.length>0){
$("tfoot input")[i].value = oSettings.aoPreSearchCols[i].sSearch;
$("tfoot input")[i].className = "";
}
}
},
"aoColumns": [
{
"sTitle": "From",
"sClass": "center",
"sWidth": "10%"
},
{
"sTitle": "To",
"sClass": "center",
"sWidth": "10%"
},
{
"sTitle": "Note",
"sClass": "center",
"sWidth": "80%"
}
]
} );
$("tfoot input").keyup( function () {
/* Filter on the column (the index) of this element */
oTable.fnFilter( this.value, $("tfoot input").index(this) );
} );
/*
* Support functions to provide a little bit of 'user friendlyness' to the textboxes in
* the footer
*/
$("tfoot input").each( function (i) {
asInitVals[i] = this.value;
} );
$("tfoot input").focus( function () {
if ( this.className == "search_init" )
{
this.className = "";
this.value = "";
}
} );
$("tfoot input").blur( function (i) {
if ( this.value == "" )
{
this.className = "search_init";
this.value = asInitVals[$("tfoot input").index(this)];
}
} );
});
For your info: I do not have a <table> ... </table> as mention before that I store my data in the array called ''my_array_data' and therefore do not have <input class="search_init"/>. Also, "my_array_data" contain three column - basically named as - "From", "To", and "Note".
Any Insight in getting 3 columns of search filter for my array "my_array_data"?
Appreciate any help offer.
#Anderson Karu yeah here is the sample for individual column filter above to header
goto herehttp://jsfiddle.net/s8F9V/1/
You need to define those 3 text boxes on your markup. Here's a shortened example of how I currently achieve the same thing using datatables:
<table id="example">
<thead>
<tr>
<th class="theader">
Date
</th>
<th class="theader">
Delay
</th>
<th class="theader">
Status
</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<th class="centered">
<input type="text" id="id1" name="id1" class="search_init" />
</th>
<th class="centered">
<input type="text" id="id2" name="id2" class="search_init" />
</th>
<th class="centered">
<input type="text" id="id3" name="id3" class="search_init" />
</th>
</tr>
</tfoot>
</table>
And my initialization code is something like:
var oTable = $("#example").dataTable({
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"iDisplayLength": 10,
"bSortClasses": false,
//...etc etc
});
$("tfoot input").keyup(function(event) {
/* Filter on the column (the index) of this element */
if (event.keyCode == 13)//only on enter pressed
{
var colIndex = getColumnIndex(this.id);//this is a custom function I wrote. Ignore it
oTable.fnFilter(this.value, colIndex);
}
});

Categories

Resources