Using conditional JavaScript (Simple)

This recipe demonstrates how to use JavaScript and Kendo templates to create dynamic content inside your Kendo Grid.

Getting ready

If you've downloaded the exercise files, open 5-javascript.html in your editor or create a new HTML file with the same name.

How to do it...

Copy the following code into your new HTML file:

<!DOCTYPE html>
<html>
<head>
<title>Kendo UI Grid How-to</title>
<link rel="stylesheet" type="text/css" href="kendo/styles/kendo.common.min.css">
<link rel="stylesheet" type="text/css" href="kendo/styles/kendo.default.min.css">
<script src="kendo/js/jquery.min.js"></script>
<script src="kendo/js/kendo.web.min.js"></script>
<script src="js/personData.js"></script>
</head>
<body>
<h3 style="color:#4f90ea;">Exercise 5 - Using Conditional JavaScript</h3>
<p><a href="EB9781849699136_3.html">Home</a></p>
<script type="text/javascript">
  $(document).ready(function() {
        var myDataSource = new kendo.data.DataSource({
         data: personData,
            schema: {
                model: {
                    fields: {
                        FirstName: { type: "string" },
                        LastName: { type: "string" },
                        Rank: { type: "string" },
                        PersonId: { type: "number" }
                    }
                }
            }
      } );
        $("#myGrid").kendoGrid({
         dataSource: myDataSource,
         columns: [
               "FirstName",
               { field: "Rank", template: kendo.template( $("#rankTemplate").html() )  }
           ]
        });
   });
</script>
<script type="text/x-kendo-template" id="rankTemplate">
   #if( Rank == 'Ghost Recon') {#
      #= Rank# !!!
   #} else {#
      #= Rank#
   #}#
</script>
<div id="myGrid"></div>
</body>
</html>

How it works...

You should have noticed several new things in this code sample. First, we actually define the columns in our grid, not just in the datasource model. Second, we have simply referenced the name of the field we wanted in the column. As a result, Kendo will render the string representation of the data and substitute a column header that matches the column name. Templates give us granular control of the presentation of each column.

Lastly, we are using a more advanced template for Rank to demonstrate how you can use JavaScript to process and evaluate the content of your grid before rendering it to the browser. Notice that the # symbol sets apart the JavaScript code included in the <script> tag. It's easier if you separate your JavaScript as is done in this example, as Kendo also looks at #= symbols to output a column field as literal text.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset