I am trying to get the most basic example of backgrid.js to work. In other words, an example where i can drop the source folder into my xampp/htdocs folder and run without having to do anything else.
I have tried many ways to get the code to run but i cannot get anything to show up.
Here is the html page i made to try to see an example working.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="bootstrap/css/bootstrap.css"/>
<link rel="stylesheet" href="lib/backgrid.css"/>
<script src="jquery-1.10.2.min.js"></script>
<script src="underscore-min.js"></script>
<script src="backbone-min.js"></script>
<script src="lib/backgrid.js"></script>
</head>
<body>
<div id="grid">
<script type="text/javascript">
var Territory = Backbone.Model.extend({});
var Territories = Backbone.Collection.extend({
model: Territory,
url: "territories.json"
});
var territories = new Territories();
var columns = [{
name: "id", // The key of the model attribute
label: "ID", // The name to display in the header
editable: false, // By default every cell in a column is editable, but *ID* shouldn't be
// Defines a cell type, and ID is displayed as an integer without the ',' separating 1000s.
cell: Backgrid.IntegerCell.extend({
orderSeparator: ''
})
}, {
name: "name",
label: "Name",
// The cell type can be a reference of a Backgrid.Cell subclass, any Backgrid.Cell subclass instances like *id* above, or a string
cell: "string" // This is converted to "StringCell" and a corresponding class in the Backgrid package namespace is looked up
}, {
name: "pop",
label: "Population",
cell: "integer" // An integer cell is a number cell that displays humanized integers
}, {
name: "percentage",
label: "% of World Population",
cell: "number" // A cell type for floating point value, defaults to have a precision 2 decimal numbers
}, {
name: "date",
label: "Date",
cell: "date"
}, {
name: "url",
label: "URL",
cell: "uri" // Renders the value in an HTML anchor element
}];
// Initialize a new Grid instance
var grid = new Backgrid.Grid({
columns: columns,
collection: territories
});
// Render the grid and attach the root to your HTML document
$("#example-1-result").append(grid.render().el);
// Fetch some countries from the url
territories.fetch({reset: true});
</script>
</div>
</body>
</html>
Thanks for your time!
You seem to be adding the grid to non-existing element:
$("#example-1-result").append(grid.render().el);
Use $("#grid") instead and you should see the result.
Related
In the examples in the documentation, I'm told I can use
table.selectRow(1);
to select row with data.id = 1 in the table.
But what if I don't know what the table object is - how do I access the table object from the containing div?, i.e.
$('#divMyTabulatorDiv).someMethod().someOtherMethod().table
What are the methods/properties I need to use to access the table component for the Tabulator grid from the HTML element's id?
You can lookup a table using the findTable function on the Tabulator prototype, passing in either a query selector or DOM node for the table:
var table = Tabulator.prototype.findTable("#example-table")[0]; // find table object for table with id of example-table
The findTable function will return an array of matching tables. If no match is found it will return false
Full details can be found in the Tabulator Options Documentation
table is the object you create, its pure Javascript driven no Html selection needed
const tabledata1 = [{
id: 1,
name: "Oli ",
money: "0",
col: "red",
dob: ""
},
{
id: 2,
name: "Mary ",
money: "0",
col: "blue",
dob: "14/05/1982"
},
{
id: 3,
name: "Christine ",
money: "0",
col: "green",
dob: "22/05/1982"
},
{
id: 4,
name: "Brendon ",
money: "0",
col: "orange",
dob: "01/08/1980"
},
{
id: 5,
name: "Margret ",
money: "0",
col: "yellow",
dob: "31/01/1999"
},
];
const col1 = [ //Define Table Columns
{
title: "Name",
field: "name",
width: 150
},
{
title: "money",
field: "money",
align: "left",
formatter: "money"
},
{
title: "Favourite Color",
field: "col"
},
{
title: "Date Of Birth",
field: "dob",
sorter: "date",
align: "center"
},
];
const table = new Tabulator("#example-table", {
data: tabledata1, //assign data to table
layout: "fitColumns", //fit columns to width of table (optional)
columns: col1,
selectable: true,
});
$('#selectRow').click(function() {
table.selectRow(1);
});
<!DOCTYPE html>
<html lang="en">
<script src="https://unpkg.com/tabulator-tables#4.2.4/dist/js/tabulator.min.js"></script>
<link href="https://unpkg.com/tabulator-tables#4.2.4/dist/css/tabulator.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div id="example-table"></div>
<button id="selectRow">Select Row 1</button>
</body>
</html>
You can use Tabulator.prototype.findTable(querySelector) (I don't know what version this was added in, but it exists in 4.5 and 4.6) to get an array of tablulators that match the querySelector.
querySelector is any valid string for document.querySelectorAll.
https://jsfiddle.net/s60qL1hw/2/
const myTable = new Tabulator("#example-table1");
const findTable = Tabulator.prototype.findTable("#example-table1");
alert('Tables are the same?\n' + (myTable === findTable[0])); // true
Once you have the table object in the variable, you can use it as the document shows.
As of v5, tabulator has a more direct way to get the table object using css selector.
If your tabulator div was like:
<div id="tabulator1"></div>
then you can get the tabulator obj into a variable by:
let table = Tabulator.findTable("#tabulator1")[0];
after this i'm able to fetch data, do changes etc:
let data = table.getData();
Ref: http://tabulator.info/docs/5.0/options#find-table
What I'd like to do is add a radio button next to the Search Bar on my datatable to allow searching by just one column, Store Number.
I was referred to drawCallback but I don't believe this does what I expect it to do. All the answers I find seem to be appending elements to rows/cols in the datatable, but not the header itself.
The selector for this header is #store-table_wrapper.
$('#store-table').DataTable({
"columnDefs": [{
"targets": [7, 8],
"visible": false,
"drawCallback": function() {
$('<input type="radio" name="store-number-filter-selector" />').appendTo('#store-table_wrapper');
}
}]
});
I believe, getting your radio button displayed you're half-way through, the really challenging part is to disable default search bar, since you're unlikely to override its default behavior (to search through the entire table).
However, you may use your own, custom searchbar, like on the following DEMO:
//define source data
const srcData = [
{id: 1, name: 'apple', category: 'fruit'},
{id: 2, name: 'raspberry', category: 'berry'},
{id: 3, name: 'carrot', category: 'vegie'}
];
//define dataTable object
const dataTable = $('#mytable').DataTable({
sDom: 't',
data: srcData,
columns: [
{data: 'id', title: 'id'},
{data: 'name', title: 'name'},
{data: 'category', title: 'category'}
],
//modify header nodes, by appending radios
initComplete: function() {
const table = this.api();
[1,2].forEach(column => table.column(column).header().innerHTML += `<input type="radio" name="searchflag" value="${column}" class="searchflag"></input>`);
}
});
//prevent sorting change upon radio click
$('input.searchflag').on('click', function(event) {
//clear search upon choosing the other radio
$('#searchfield').val('');
dataTable.search('').columns().search('').draw();
event.stopPropagation();
});
//searchbar keyup callback
$('#searchfield').on('keyup', function() {
//grab checked radio button value or search the entire table by default
let targetColumn = null;
targetColumn = $('input.searchflag:checked').val();
if(!targetColumn){
dataTable.search($(this).val()).draw();
}
else {
dataTable.column(targetColumn).search($(this).val()).draw();
}
})
input.searchflag {
float: left;
}
<!doctype html>
<html>
<head>
<script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="application/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="demo.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</head>
<body>
<input id="searchfield"></input>
<table id="mytable"></table>
</body>
</html>
I need to show an array of objects in the table like representation. Table has columns with the properties, and when clicked on the column it should show more data inside the table. It should be sortable.
Is there a JS library that could do this, so I dont have to write this from scratch?
Please see the attached image with the JSON object.
When the user clicks on Ana, additional row is inserted.
I created the demo https://jsfiddle.net/OlegKi/kc2537ty/1/ which demonstrates the usage of free jqGrid with subgrids. It displays the results like
after the user clicks on the "+" icon in the second line.
The corresponding code you can find below
var mydata = [
{ id: 10, name: "John", lname: "Smith", age: 31, loc: { location: "North America", city: "Seattle", country: "US" } },
{ id: 20, name: "Ana", lname: "Maria", age: 43, loc: { location: "Europe", city: "London", country: "UK" } }
];
$("#grid").jqGrid({
data: mydata,
colModel: [
{ name: "name", label: "Name" },
{ name: "lname", label: "Last name" },
{ name: "age", label: "Age", template: "integer", align: "center" }
],
cmTemplate: { align: "center", width: 150 },
sortname: "age",
iconSet: "fontAwesome",
subGrid: true,
subGridRowExpanded: function (subgridDivId, rowid) {
var $subgrid = $("<table id='" + subgridDivId + "_t'></table>"),
subgridData = [$(this).jqGrid("getLocalRow", rowid).loc];
$("#" + subgridDivId).append($subgrid);
$subgrid.jqGrid({
idPrefix: rowid + "_",
data: subgridData,
colModel: [
{ name: "location", label: "Localtion" },
{ name: "city", label: "City" },
{ name: "country", label: "Country" }
],
cmTemplate: { align: "center" },
iconSet: "fontAwesome",
autowidth: true
});
}
});
Small comments to the code. Free jqGrid saves all properties of input data in data parameter. I added id property to every item of input data. It's not mandatory, but it could be helpful if you would add more functionality to the grid. See the introduction for more details.
The columns are sortable based on the type of the data specified by sorttype property of colModel. To simplify usage some standard types of data free jqGrid provides some standard templates which are shortcurts for some set of settings. I used template: "integer" in the demo, but you could replace it to sorttype: "integer" if only sorting by integer functionality is important.
If the user click on "+" icon to expand the subgrid then jqGrid inserts new row and creates the div for the data part of the subgrid. You can replace subGridRowExpanded from above example to the following
subGridRowExpanded: function (subgridDivId) {
$("#" + subgridDivId).html("<em>simple subgrid data</em>");
}
to understand what I mean. The unique id of the div will be the first parameter of the callback. One can create any common HTML content in the subgrid. Thus one can create empty <table>, append it to the subgrid div and
then convert the table to the subgrid.
To access to the item of data, which corresponds to the expanding row one can use $(this).jqGrid("getLocalRow", rowid). The return data is the item of original data. It has loc property which we need. To be able to use the data as input for jqGrid we create array with the element. I's mostly all, what one have to know to understand how the above code works.
You can add call of .jqGrid("filterToolbar") to be able to filter the data or to add pager: true (or toppager: true, or both) to have the pager and to use rowNum: 5 to specify the number of rows in the page. In the way you can load relatively large set of data in the grid and the user can use local paging, sorting and filtering. See the demo which shows the performance of loading, sorting and filtering of the local grid with 4000 rows and another one with 40000 rows. All works pretty quickly if one uses local paging and not displays all the data at once.
I use datatables.net for all my "more complex than lists"-tables. I It's a very well kept library with loads of features and great flexibility.
In the "con" column I would say that it's so complex that it probably has quite a steep learning curve. Although the documentation is great so there is always hope for most problems.
I am displaying some data in a slickgrid using ajax call which looks similar like this.
india 564
usa 45454
japan 5454
There is no column called a 'Number' which have the row number values,in the data table I am fetching. How can I set a column called 'Number' and set values? What I want is something similar like this.
1 india 564
2 usa 45454
3 japan 5454
To display the row number, you don't need a specific field/property for it. You can define a column and specify the formatter column option to return a value based on the underlying indexing of the grid which the function receives as it's first argument. Since the grid is 0 index based, adjust accordingly.
var grid;
var dataView = new Slick.Data.DataView();
var data = [{country: "usa", number: "123"},
{country: "japan", number: "456"},
{country: "india", number: "789"}];
var options = {
editable: false,
enableCellNavigation: true
};
var columns = [{name: "Row No", formatter: function(row){return row+1}},
{field: "country", name: "Country"},
{field: "number", name: "Data"}];
dataView.setItems(data, 'country')
grid = new Slick.Grid("#myGrid", dataView, columns, options);
<link rel="stylesheet" type="text/css" href="http://mleibman.github.io/SlickGrid/slick.grid.css">
<link rel="stylesheet" href="http://mleibman.github.io/SlickGrid/examples/examples.css" type="text/css"/>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.0/jquery-ui.min.js"></script>
<script src="http://mleibman.github.io/SlickGrid/lib/jquery.event.drag-2.2.js"></script>
<script src="http://mleibman.github.io/SlickGrid/slick.core.js"></script>
<script src="http://mleibman.github.io/SlickGrid/slick.grid.js"></script>
<script src="http://mleibman.github.io/SlickGrid/slick.dataview.js"></script>
<div id="myGrid" style="width:300px;height:150px;"></div>
I use Kendo UI Grid for displaying array data with objects having some fields missing. Here is js code:
var arr = [{b: "b1"}, {a: "a2", b: "b2"}];
$("#grid").kendoGrid({
dataSource: arr,
columns: [
{
title: "The A column",
field: 'a'
}, {
title: "The B column",
template: '<i>#=b#</i>'
}]
});
In this example the grid works well and displays missing "a" value in first row as empty cell.
When working with column template:
$("#grid").kendoGrid({
dataSource: arr,
columns: [
{
title: "The A column",
template: '<b>#=a#</b>'
}, {
title: "The B column",
template: '<i>#=b#</i>'
}]
});
It displays an error in console: Uncaught ReferenceError: a is not defined.
Even replacing template with:
template: '<b>#=a || ""#</b>'
expression instead does not help, so I have to manually set the missing values to empty string before constructing the table. Is there way to avoid this?
Instead of:
template: '<b>#=a || ""#</b>'
You should use:
template: '<b>#=data.a || ""#</b>'
Where data is predefined by KendoUI and is equal to the row data. Otherwise JavaScript doesn't know that a should be part of the data and thinks that it is a variable per-se throwing the error.
You can see it running in the following snippet
$(document).ready(function() {
var arr = [{b: "b1"}, {a: "a2", b: "b2"}];
$("#grid").kendoGrid({
dataSource: arr,
columns: [
{
title: "The A column",
template: '<b>#= data.a || ""#</b>'
}, {
title: "The B column",
template: '<i>#=b#</i>'
}]
});
});
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.429/styles/kendo.common.min.css">
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.429/styles/kendo.default.min.css">
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://cdn.kendostatic.com/2015.1.429/js/kendo.all.min.js"></script>
<div id="grid"></div>