Reputation: 751
I am generating the dataTable
from xml
data. I want to change the column visibility based upon the column name. I Do not want to hard code the value for targets
like 2 or 3 and also I do not want to set based on the class name.
$(document).ready(function() {
var dataOptions = {
{
"columnDefs": [ {
"visible": false,
"targets":2
} ]
}
};
$('#example').dataTable( dataOptions );
} );
#Edit
My XML DATA
<root>
<filterStartDate>2006-11-18</filterStartDate>
<filterEndDate>2015-02-11</filterEndDate>
<responseCount>0</responseCount>
<responseCountFormatted></responseCountFormatted>
<metadata>
<columns>
<column name="startDate" type="DATE" nameT="Start Date" sortable="true" />
<column name="endDate" type="DATE" nameT="End Date" sortable="true" />
<column name="COMPANY_ID" type="STRING" nameT="Company" sortable="true" />
<column name="COMPANY_ID___code" type="STRING" nameT="Company" visible="false" />
<column name="multipleGroupBy" type="STRING" nameT="Multiple Group By" visible="false" />
</columns>
</metadata>
<pageInformation><totalPages>1</totalPages><totalRows>10</totalRows><pageStart>0</pageStart><pageEnd>10</pageEnd><rowsPerPage>50</rowsPerPage></pageInformation>
<data>
<row startDate="2006-11-18" endDate="2015-02-11" COMPANY_ID="CONSUMER" COMPANY_ID___code="CONSUMER" multipleGroupBy="|CONSUMER">
</row>
</data>
</root>
Can I achieve this in a better way...
Upvotes: 0
Views: 12133
Reputation: 11
You just need to change the value of i dynamically
define the var i = 2; and assign this i value to "targets":i and then change value of i as you want
Upvotes: 0
Reputation: 85578
Looks straight forward to me, like the XML is generated specifically to dataTables or is based on a dataTables instance itself. When you wrote "I want to change the column visibility based upon the column name" I guess you mean the column attribute visible
?
var parser = new DOMParser(),
doc = parser.parseFromString(xml, "application/xml"),
columns = doc.querySelectorAll('column'),
options = { columnDefs:[] },
column;
for (var i=0;i<columns.length;i++) {
column = columns[i];
options.columnDefs.push({
data : column.getAttribute('name'),
title : column.getAttribute('nameT'),
type : column.getAttribute('type'),
visible : column.getAttribute('visible') == 'false' ? false : true,
sortable : column.getAttribute('sortable'),
targets : i
});
}
var table = $('#example').DataTable(options);
demo -> http://jsfiddle.net/pbtb8h42/ Sorry if I misunderstood the question.
Upvotes: 1