Dynamically creating a layered Javascript object for jQuery-jTable

Layout

jTable (jTable.org) is defined by the code below. I want to build it dynamically (based on AJAX return from a database query).

{ title: 'My Dynamic Title', fields: { id: { title: 'ID' }, salesperson: { title: 'Salesperson' }, pivot1: { title: '2012-01' }, pivot2: { title: '2012-02' }, pivot3: { title: '2012-03' } } } 

The data displayed is a pivot table, so the number of columns and their headers will change. Is it possible for me to dynamically change the field section above? for example, have four columns with corresponding column headings.

Answer

I realized this thanks to Barmar and extensive reading. The trick is to insert a new object at each level. Pop this in jsfiddle.net and you can see the result. It will programmatically create the object above.

 var myobj = {}; //description for jquery-jtable configuration. var colnames = ['pivot1', 'pivot2', 'pivot3']; var titles = ['2012-01', '2012-02', '2012-03']; myobj['title'] = "My Dynamic Title"; myobj['fields'] = {}; //create a second level under 'fields'. myobj.fields['id'] = {title: 'ID'}; myobj.fields['salesperson'] = {title: 'Salesperson'}; for(i = 0; i < colnames.length; i++) { myobj.fields[colnames[i]] = {}; //create a third level under column name. myobj.fields[colnames[i]].title = titles[i]; } alert(JSON.stringify(myobj, null, 4)); 
+4
source share
1 answer

I do not see a method for dynamically changing a field specification. But if you modify the table, you can simply destroy the old jTable and reinitialize it:

 $("#TableContainer").jtable("destroy"); $("#TableContainer").jtable({ // New options }); 

If there are several options that will remain consistent across all instances, you can use a variable to store options:

 var jtable_options = { title: "My Table Title", fields: {} }; 

Before initializing jtable, do the following:

 jtable_options.fields = { id: { title: 'ID' }, salesperson: { title: 'Salesperson' } ... }; $("#TableContainer").jtable(jtable_options); 
+4
source

Source: https://habr.com/ru/post/1502169/


All Articles