сряда, 15 януари 2014 г.

JavaScript Grid From Table

In this blog entry, we look at binding the ShieldUI Grid to data located in a table element on the page. 
Bacause of the flexible binding mechanism of the ShieldUI DataSource control, this task is achieved easily with little code. 
In order to be able to render the grid on the page, we first add a div element, which will host our widget. 
Its simple declaration looks like this:
<div id="grid"></div>

The table, which will provide data for the grid looks like this:

<table id="dataTable">
    <thead>
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Category</th>
            <th>Date</th>
            <th>Available</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1</td>
            <td>Item 1</td>
            <td>3</td>
            <td>2013/11/1</td>
            <td>true</td>
        </tr>
        <tr>
            <td>2</td>
            <td>Item 2</td>
            <td>1</td>
            <td>2013/10/31 22:30</td>
            <td>false</td>
        </tr>
        <tr>
            <td>3</td>
            <td>Item 3</td>
            <td>2</td>
            <td>2013/11/1 10:40 PM</td>
            <td>0</td>
        </tr>
    </tbody>
</table>

It is important to include an ID for the table element, because this will later be required by the DataSource component. 
There is only one more step needed to visualize the data and be able to use the automatic grid features, such as paging or sorting. This is to include the declaration of the grid itself. This looks like this:

<script type="text/javascript">
    $(document).ready(function () {
        $("#grid").shieldGrid({
            sorting: true,
            dataSource: {
                data: "#dataTable",
                schema: {
                    type: "table",
                    fields: {
                        Id: { type: "number" },
                        Name: { type: "string" },
                        Category: { type: "number" },
                        Date: { type: "date" },
                        Available: { type: "boolean" }
                    }
                }
            },
            columns: [
                { field: "Id" },
                { field: "Name" },
                { field: "Category" },
                { field: "Date" },
                { field: "Available" }
            ]
        });
    });
</script>

You can view a fully functional example, demonstrating the code listed above, in the following location.

Няма коментари:

Публикуване на коментар