Showing posts with label table. Show all posts
Showing posts with label table. Show all posts

Thursday, May 24, 2012

Show/hide detail in a table using jQuery and MVC 3

This is another simple example where we will be showing some record in a table and there will be some plus/ minus image in each row and on click of the image we will be showing some detail of the record. And we will toggle the images and data. To do that lets have the following view models-
namespace MVCRazor.ViewModel
{
    public class TableRowItemViewlModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public TableRowItemDetailViewlModel Detail { get; set; }
    }
    public class TableRowItemDetailViewlModel
    {
        public string Address { get; set; }
        public string Sex { get; set; }
        public string Nationality { get; set; }
    }
}
The model is simple and self explanatory. And we are going to use the following view to display the tabular data and the controller to read the data. In the sample we have taken some in memory object for data access-
namespace MVCRazor.Controllers
{
    public class TableRowDetailController : Controller
    {
        List<TableRowItemViewlModel> data = new List<TableRowItemViewlModel>();
        public TableRowDetailController()
        {
            data.AddRange(new List<TableRowItemViewlModel>(){
            new TableRowItemViewlModel(){ Id =1,Name="Name 1", Email ="Email 1", Detail=new TableRowItemDetailViewlModel(){Address="Address 1", Nationality="Nationality 1", Sex="Sex 1"}},
            new TableRowItemViewlModel(){ Id =2,Name="Name 2", Email ="Email 2", Detail=new TableRowItemDetailViewlModel(){Address="Address 2", Nationality="Nationality 2", Sex="Sex 2"}},
            new TableRowItemViewlModel(){ Id =3,Name="Name 3", Email ="Email 3", Detail=new TableRowItemDetailViewlModel(){Address="Address 3", Nationality="Nationality 3", Sex="Sex 3"}},
            new TableRowItemViewlModel(){ Id =4,Name="Name 4", Email ="Email 4", Detail=new TableRowItemDetailViewlModel(){Address="Address 4", Nationality="Nationality 4", Sex="Sex 4"}},
            new TableRowItemViewlModel(){ Id =5,Name="Name 5", Email ="Email 5", Detail=new TableRowItemDetailViewlModel(){Address="Address 5", Nationality="Nationality 5", Sex="Sex 5"}},
            new TableRowItemViewlModel(){ Id =6,Name="Name 6", Email ="Email 6", Detail=new TableRowItemDetailViewlModel(){Address="Address 6", Nationality="Nationality 6", Sex="Sex 6"}},
            new TableRowItemViewlModel(){ Id =7,Name="Name 7", Email ="Email 7", Detail=new TableRowItemDetailViewlModel(){Address="Address 7", Nationality="Nationality 7", Sex="Sex 7"}},
            new TableRowItemViewlModel(){ Id =8,Name="Name 8", Email ="Email 8", Detail=new TableRowItemDetailViewlModel(){Address="Address 8", Nationality="Nationality 8", Sex="Sex 8"}},
            new TableRowItemViewlModel(){ Id =9,Name="Name 9", Email ="Email 9", Detail=new TableRowItemDetailViewlModel(){Address="Address 9", Nationality="Nationality 9", Sex="Sex 9"}},
        });
        }

        public ActionResult Index()
        {
            return View((from c in data
                         select new TableRowItemViewlModel() { Id = c.Id, Name = c.Name, Email = c.Email }).ToList());
        }
    }
}
@model List<MVCRazor.ViewModel.TableRowItemViewlModel>
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<style>
.tbl {border:1px solid gray; }
.tbl td{padding:5px 10px 5px 10px; }
.tbl th{padding:5px 10px 5px 10px;background-color:Gray;color:White }
.pm{ cursor:pointer;}
.plus
{
    background:url('http://www.quimicasuiza.com/images/extras/plus-minus.gif') 0 -16px;
    display:block;
    width:16px;
    height:16px;
}
.minus
{
    background:url('http://www.quimicasuiza.com/images/extras/plus-minus.gif') 0 0;
    display:block;
    width:16px;
    height:16px;
}
.detail
{
    background-color:#d4d0d8;    
    padding:7px;
}
</style>
<table class="tbl" cellpadding="0" cellspacing="0">
<tr><th>&nbsp;</th><th>Id</th><th>Name</th><th>Email</th></tr>
@foreach (var row in Model)
{ 
    <tr><td><span class="pm plus"></span></td><td>@row.Id</td><td>@row.Name</td><td>@row.Email</td></tr>
}
</table>
The above controller and the view will display the data like below-
We are going to use the following script to retrieve data from the controller and show hide the details.
<script type="text/javascript">
    var colCount;
    $(document).ready(function () {
        colCount = $(".tbl tr:first").children().length;
        $("tr:odd").css("background-color", "#f0f3f4");
        $(".pm").click(function () {
            if ($(this).hasClass("plus")) {
                $(this).removeClass("plus").addClass("minus");
                if (!$(this).closest("tr").next().hasClass("detail")) {
                    getDetail($(this).closest("tr"));
                }
                else
                    $(this).closest("tr").next().show();
            }
            else {
                if ($(this).closest("tr").next().hasClass("detail"))
                    $(this).closest("tr").next().hide();
                $(this).removeClass("minus").addClass("plus");
            }
        });
    });
    function getDetail(row) {
        var rowNew = $("<tr class='detail'><td colspan=" + colCount + "></td></tr>");
        $.ajax({
            type: "get",
            timeout: 30000,
            data: "id=" + row.find("td:eq(1)").html(),
            url: '@Url.Action("GetDetail")',
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function (result) {
                rowNew.find("td").append("<b>Address </b>: " + result.Address);
                rowNew.find("td").append("<br /><b>Sex </b>: " + result.Sex);
                rowNew.find("td").append("<br /><b>Nationality </b>: " + result.Nationality);
                row.after(rowNew);
            },
            error: function (a, b, c) {
                debugger;
            }
        });
    }
</script>
In this we are showing plus/minus button as span with CSS class pm. On click of the span we are checking whether it has a class named plus . Based on that in line 8 and 18 we are toggling the classes plus/minus.

If the line has class called plus, in the line 9 we are checking whether the next row of the container row has a CSS class called detail. Suppose it has that class then we are simply showing that row(in line 13). Otherwise we are calling a function called getDetail in line 10 by passing the current row. In that function we are building a row in memory with same columnspan as of the table row. Then we are passing the id of row and doing a ajax call to the controller to get the data. In the success of the ajax call we are adding the newly created row next to the current row(in line 37).

On click of span, if the condition check in the line 7 does not have a class named plus, that means the detail is already loaded and open. We are simply hiding the detail in line(16-17).

The controller method for getting detail is as follows-
        public JsonResult GetDetail(int id)
        {
            return Json((from c in data
                         where c.Id == id
                         select c.Detail).First(), JsonRequestBehavior.AllowGet);
        }
In the image we can see things in action. If we click the button multiple time, the ajax call will happen one time only. And on subsequent click it just show and hide the data.

Thursday, May 17, 2012

Calculating row total, column total, grand total if a table or gridview using jQuery

In this post lets discuss a very common problem. I have answered many such posts. Finally I decided to write a blog post on it. This is regarding calculating the total of the columns, total of the rows and grand total in a table. For this case lets take textbox in each cell and on keyup we are going to do the calculation. And the code goes here-
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $(".data").keyup(function () {
                var temp, total = 0, index;
                $(this).closest("tr").find(".data").each(function (i, item) {
                    temp = parseFloat($(item).val());
                    if (!isNaN(temp))
                        total = total + temp;
                });
                $(this).closest("tr").find(".rowTotal").val(total);
                total = 0;
                index = $(this).closest("tr").find("td").index($(this).closest("td"));
                $("#tbl tr").each(function (i, item) {

                    if ($(item).find("td:eq(" + index + ") .data").hasClass("data")) {
                        temp = parseFloat($(item).find("td:eq(" + index + ") .data").val());
                        if (!isNaN(temp))
                            total = total + temp;
                    }
                });
                $("#tbl tr:last td:eq(" + index + ") .columnTotal").val(total);
                calculateGrandTotal();
            })
        });
        function calculateGrandTotal() {
            (function () {
                var temp, total = 0;
                $(".columnTotal").each(function () {
                    temp = parseFloat($(this).val());
                    if (!isNaN(temp))
                        total = total + temp;
                });
                $(".grandTotal").val(total);
            })();
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <table id="tbl">
    <tr>
        <td><asp:TextBox ID="TextBox1" CssClass="data" runat="server"></asp:TextBox></td>
        <td><asp:TextBox ID="TextBox2" CssClass="data" runat="server"></asp:TextBox></td>
        <td><asp:TextBox ID="TextBox3" CssClass="data" runat="server"></asp:TextBox></td>
        <td><asp:TextBox ID="TextBox4" CssClass="data" runat="server"></asp:TextBox></td>
        <td><asp:TextBox ID="TextBox5" CssClass="rowTotal" ReadOnly="true" runat="server"></asp:TextBox></td>
    </tr>
        <tr>
        <td><asp:TextBox ID="TextBox6" CssClass="data" runat="server"></asp:TextBox></td>
        <td><asp:TextBox ID="TextBox7" CssClass="data" runat="server"></asp:TextBox></td>
        <td><asp:TextBox ID="TextBox8" CssClass="data" runat="server"></asp:TextBox></td>
        <td><asp:TextBox ID="TextBox9" CssClass="data" runat="server"></asp:TextBox></td>
        <td><asp:TextBox ID="TextBox10" CssClass="rowTotal" ReadOnly="true" runat="server"></asp:TextBox></td>
    </tr>
        <tr>
        <td><asp:TextBox ID="TextBox11" CssClass="data" runat="server"></asp:TextBox></td>
        <td><asp:TextBox ID="TextBox12" CssClass="data" runat="server"></asp:TextBox></td>
        <td><asp:TextBox ID="TextBox13" CssClass="data" runat="server"></asp:TextBox></td>
        <td><asp:TextBox ID="TextBox14" CssClass="data" runat="server"></asp:TextBox></td>
        <td><asp:TextBox ID="TextBox15" CssClass="rowTotal" ReadOnly="true" runat="server"></asp:TextBox></td>
    </tr>
        <tr>
        <td><asp:TextBox ID="TextBox16" CssClass="data" runat="server"></asp:TextBox></td>
        <td><asp:TextBox ID="TextBox17" CssClass="data" runat="server"></asp:TextBox></td>
        <td><asp:TextBox ID="TextBox18" CssClass="data" runat="server"></asp:TextBox></td>
        <td><asp:TextBox ID="TextBox19" CssClass="data" runat="server"></asp:TextBox></td>
        <td><asp:TextBox ID="TextBox20" CssClass="rowTotal" ReadOnly="true" runat="server"></asp:TextBox></td>
    </tr>
        <tr>
        <td><asp:TextBox ID="TextBox21" CssClass="columnTotal" ReadOnly="true" runat="server"></asp:TextBox></td>
        <td><asp:TextBox ID="TextBox22" CssClass="columnTotal" ReadOnly="true" runat="server"></asp:TextBox></td>
        <td><asp:TextBox ID="TextBox23" CssClass="columnTotal" ReadOnly="true" runat="server"></asp:TextBox></td>
        <td><asp:TextBox ID="TextBox24" CssClass="columnTotal" ReadOnly="true" runat="server"></asp:TextBox></td>
        <td><asp:TextBox ID="TextBox25" CssClass="grandTotal" ReadOnly="true" runat="server"></asp:TextBox></td>
    </tr>
    </table>
    </form>
    </body>
</html>

Sunday, March 11, 2012

Copy or duplicate column data in a table using context menu

This is a simple post used to copy data in a cell of a table to other cells of the same column. For this post we will be using a very simple HTML layout as follows-
<table>
<tr>
<th>data 1</th><th>data 2</th>
</tr>
<tr>
<td><input type="text" /> </td>
<td><input type="text" /> </td>
</tr>
<tr>
<td><input type="text" /> </td>
<td><input type="text" /> </td>
</tr>
<tr>
<td><input type="text" /> </td>
<td><input type="text" /> </td>
</tr>
<tr>
<td><input type="text" /> </td>
<td><input type="text" /> </td>
</tr>
<tr>
<td><input type="text" /> </td>
<td><input type="text" /> </td>
</tr>
</table>
For context menu we are going to use this plugin.

For content menu we are using the following HTML for the menu content, which include two options- copy and cancel. HTML for the context menu is as follows-
    <ul id="myMenu" class="contextMenu">
<li class="copy"><a href="#copy">Copy value</a></li>
<li class="quit separator"><a href="#cancel">Cancel</a></li>
</ul>
For implementing the context menu we need to take the following files references or we can download from the desired location-
    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.js" type="text/javascript"></script>
<script src="http://labs.abeautifulsite.net/archived/jquery-contextMenu/demo/jquery.contextMenu.js"
type="text/javascript"></script>
<link href="http://labs.abeautifulsite.net/archived/jquery-contextMenu/demo/jquery.contextMenu.css"
rel="stylesheet" type="text/css" />
Now we can use following JavaScript code for copying/duplicating the data in a column-
    <script type="text/javascript">
$(document).ready(function () {
$("table input").contextMenu({
menu: 'myMenu'
}, function (action, el, pos) {
if (action == "copy") {
index = el.closest("tr").children().index(el.parent()[0]);
$("table tr").each(function (i, item) {
$(item).find("td:eq(" + index + ") input").val(el.val());
})
}
});
});
</script>