Find odd and even rows using $.inArray() function when using jQuery Templates

Posted by hajan on Weblogs See other posts from Weblogs or by hajan
Published on Mon, 10 Jan 2011 20:26:00 GMT Indexed on 2011/01/10 22:54 UTC
Read the original article Hit count: 285

Filed under:

In the past period I made series of blogs on ‘jQuery Templates in ASP.NET’ topic.

In one of these blogs dealing with jQuery Templates supported tags, I’ve got a question how to create alternating row background.

When rendering the template, there is no direct access to the item index. One way is if there is an incremental index in the JSON string, we can use it to solve this. If there is not, then one of the ways to do this is by using the jQuery’s $.inArray() function.

- $.inArray(value, array) – similar to JavaScript indexOf()

Here is an complete example how to use this in context of jQuery Templates:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">

<html xmlns="" >
<head runat="server">
    <style type="text/css">
        #myList { cursor:pointer; }
        .speakerOdd { background-color:Gray; color:White;}
        .speaker { background-color:#443344; color:White;}
        .speaker:hover { background-color:White; color:Black;}
        .speakerOdd:hover { background-color:White; color:Black;}
    <title>jQuery ASP.NET</title>
    <script src="" type="text/javascript"></script>
    <script src="" type="text/javascript"></script>
    <script language="javascript" type="text/javascript">
        var speakers = [
            { Name: "Hajan1" },
            { Name: "Hajan2" },
            { Name: "Hajan3" },
            { Name: "Hajan4" },
            { Name: "Hajan5" }

        $(function () {

        function oddOrEven() {
            return ($.inArray(, speakers) % 2) ? "speaker" : "speakerOdd";

    <script id="myTemplate" type="text/x-jquery-tmpl">
        <tr class="${oddOrEven()}">
            <td> ${Name}</td>
    <table id="myList"></table>

So, I have defined stylesheet classes speakerOdd and speaker as well as corresponding :hover styles.

Then, you have speakers JSON string containing five items. And what is most important in our case is the oddOrEven function where $.inArray(value, data) is implemented.

function oddOrEven() {
    return ($.inArray(, speakers) % 2) ? "speaker" : "speakerOdd";

Remark: The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0.

So, now we can call oddOrEven function from inside our jQuery Template in the following way:

<script id="myTemplate" type="text/x-jquery-tmpl">
    <tr class="${oddOrEven()}">
        <td> ${Name}</td>

And the result is

I hope you like it.


© Weblogs or respective owner

Related posts about ASP.NET

Related posts about jQuery Templates