Allow just numbers jquery for inputbox


 $(‘.onlynumber’).keydown(function (e) {
                if (e.shiftKey || e.ctrlKey || e.altKey) {
                    e.preventDefault();
                } else {
                    var key = e.keyCode;
                    if (!((key == 8) || (key == 46) || (key >= 35 && key <= 40) || (key >= 48 && key <= 57) || (key >= 96 && key <= 105))) {
                        e.preventDefault();
                    }
                }
            });

Advertisements

Allow only numbers and single decimal into inputbox using jquery


  function onlyDecimal(element, decimals) {
                $(element).keypress(function (event) {
                    var num = $(this).val();
                    num = isNaN(num) || num === ” || num === null ? 0.00 : num;
                    if ((event.which != 46 || $(this).val().indexOf(‘.’) != -1) && (event.which < 48 || event.which > 57)) {
                        event.preventDefault();
                    }
                    if ($(this).val() == parseFloat(num).toFixed(decimals)) {
                        event.preventDefault();
                    }
                });
            }
            onlyDecimal($(‘.singledecimalandnumber’), 2);

Creating an expandable master-details table using DataTable Plugin of jQuery


Hello Friends today i need to display master details so i decided to do rnd on net after lot of effort i found a good jQuery datatable plugin that’s really awesome and intellgent.

if you want to creating fully functional tables with pagination, sorting, filtering features is an easy task if you use the jQuery DataTables plug-in. This plug-in enables you to add all of these functionalities to a plain HTML table using a single line of code as shown in the following example:

(‘#mygrid’).datatable();

but before this you will have to need some files such as jQuery Datatable and themes file.

Now i will explain u step by step my jQuery Datatable  plugin article.basically in this practical is composed in MVC3 +Razor view Engine and Entity Framework.

in my sample have Three views

1) Index –display to static static data

2) Server Side — display server side data of Action method using ajax request and also have Model help.

3) Ajax Loading — Display using complete ajax request data on view without model class help.

 

Step 1) First of all you will have to make a New Empty MVC3 Project using Visual Studio 2010 as below given in image :

Image

Step 2 : Now Make DataBase dbNestedDataTable and In that add Two Tables and Also add Some Dummy entries those tables.

for help you can use to below given sqlscript.

USE dbNestedDataTable

go

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Company]’) AND type in (N’U’))
BEGIN
CREATE TABLE [dbo].[Company](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [varchar](50) NULL,
    [Address] [varchar](100) NULL,
 CONSTRAINT [PK_Company] PRIMARY KEY CLUSTERED
(
    [ID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Employee]’) AND type in (N’U’))
BEGIN
CREATE TABLE [dbo].[Employee](
    [EmployeeID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [varchar](50) NULL,
    [Position] [varchar](50) NULL,
    [Phone] [varchar](50) NULL,
    [Email] [varchar](50) NULL,
    [CompanyID] [int] NULL,
 CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED
(
    [EmployeeID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
END
GO
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_Employee_Company]’) AND parent_object_id = OBJECT_ID(N'[dbo].[Employee]’))
ALTER TABLE [dbo].[Employee]  WITH CHECK ADD  CONSTRAINT [FK_Employee_Company] FOREIGN KEY([CompanyID])
REFERENCES [dbo].[Company] ([ID])
Step 3: Now Come back in ur web application and now add a controller by right click on controller folder with name of HomeController.

Image

Step 4 : Now go into home controller u will see a index action and by right click on View and Click on AddView u will get a new view in View->Home->index.cshtml as below given image.

 

 

 

 

 

Image

Step 5 : Now Click on Index.cshtml view and go into it’s source  and paste below given code.

@{
    ViewBag.Title = "Index";
}
 
    @section onReady
    {
    var oTable;
$('#companies tbody td img').click(function () {
    var nTr = this.parentNode.parentNode;
    if (this.src.match('Math-minus-icon')) {
        /* This row is already open - close it */
        this.src = "/Content/Math-plus-icon.png";
        oTable.fnClose(nTr);
    }
    else {
        /* Open this row */
        this.src = "/Content/Math-minus-icon.png";
        var companyid = $(this).attr("rel");
        $.get("@Url.Action("CompanyEmployees","Home")?companyID=" + companyid, function (employees) {
            oTable.fnOpen(nTr, employees, 'details');
        });
    }
        });
        /* Initialize table and make first column non-sortable*/
oTable = $('#companies').dataTable({  "bJQueryUI": true,
                                        "aoColumns": [
                                        {   "bSortable": false,
                                            "bSearchable": false },
                                        null,
                                        null,
                                        null
                                ]
    });
}
 
<div id="demo">
    <table id="companies" class="display">
        <thead>
            <tr>
                <th>
                </th>
                <th>
                    Company name
                </th>
                <th>
                    Address
                </th>
                <th>
                    Town
                </th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>
                    <img src="/Content/Math-plus-icon.png" rel="1" style="cursor:pointer;" alt="expand/collapse">
                </td>
                <td>
                    Emkay Entertainments
                </td>
                <td>
                    Nobel House, Regent Centre
                </td>
                <td>
                    Lothian
                </td>
            </tr>
            <tr>
                <td>
                    <img src="/Content/Math-plus-icon.png" rel="2" style="cursor:pointer;" alt="expand/collapse">
                </td>
                <td>
                    The Empire
                </td>
                <td>
                    Milton Keynes Leisure Plaza
                </td>
                <td>
                    Buckinghamshire
                </td>
            </tr>
        </tbody>
    </table>
</div>

Step 6: Now You will have to go in _Layout.chstml page that's in Shared Folder in which you will
add some resources link and url which are below given.
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
    <link href="@Url.Content("~/Content/dataTables/demo_page.css")" rel="stylesheet" type="text/css" />
        <link href="@Url.Content("~/Content/dataTables/demo_table.css")" rel="stylesheet" type="text/css" />
        <link href="@Url.Content("~/Content/dataTables/demo_table_jui.css")" rel="stylesheet" type="text/css" />
        <link href="@Url.Content("~/Content/themes/base/jquery-ui.css")" rel="stylesheet" type="text/css" media="all" />
        <link href="@Url.Content("~/Content/themes/smoothness/jquery-ui-1.10.3.custom.min.css")"rel="stylesheet" type="text/css" media="all" />
        <script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
        <script src="@Url.Content("~/Scripts/jquery.dataTables.min.js")" type="text/javascript"></script>
        <script src="@Url.Content("~/Scripts/jquery-ui.js")" type="text/javascript"></script>
    <script language="javascript" type="text/javascript">
        $(document).ready(function () {
            @RenderSection("onReady", required: false)
        });
    </script>
</head>
<body>
    <header class="ui-state-processing">
        <ul>
            <li>
        @Html.ActionLink("Static table", "Index", "Home")        
            </li>
        
        
            <li>@Html.ActionLink("Server-side generated table", "ServerSide", "Home")</li>
 
       <li> @Html.ActionLink("Ajax-loaded table", "Ajax", "Home")</li>
        </ul>
    </header>
    <div class="ui-widget-content">
        @RenderBody()
    </div>
</body>
</html>

Step 7 : Now Add new Entity model by right click on Model Folder and make connection with your database which u have been made in MSSQLSERVER and then
you will see that your application will give u below type image.
Image
Image
Step 8: Now add Two Methods in your home controller.
   public ActionResult CompanyEmployees(int? companyID)
        {
            var employees = GetEmployees();
            var companyEmployees = (from e in employees
                                    where (companyID == null || e.CompanyID == companyID)
                                    select e).ToList();
            return PartialView("CompanyEmployees", companyEmployees);
        }
        public IEnumerable<Employee> GetEmployees()
        {
            using (var db = new dbNestedDataTableEntities())
            {
                return db.Employees.ToList();
            }
        }
and complie then run by pressing F5 on Index page you will see that look as below given.
Image

Upto this you will get data static data display how using datatable plugin in
MVC3
now you will do Second Thing ServerSide Data How Bind to DataTable in MVC From View Action.
Add Two Method in Your homecontroller
  public ActionResult ServerSide()
        {
            var obj = GetCompanies();
            return View(obj);
        }
        public IEnumerable<Company> GetCompanies()
        {
            using (var db = new dbNestedDataTableEntities())
            {
                return db.Companies.ToList();
            }
        }
and Add a new view whose name is ServerSide.cshtml
in which source code will be such as.
@model IEnumerable< mvcwithnesteddatatable.Models.Company>
@{
    ViewBag.Title = "ServerSide";
}
@section onReady
    {
    var oTable;
$('#companies tbody td img').click(function () {
    var nTr = this.parentNode.parentNode;
    if (this.src.match('Math-minus-icon')) {
        /* This row is already open - close it */
        this.src = "/Content/Math-plus-icon.png";
        oTable.fnClose(nTr);
    }
    else {
        /* Open this row */
        this.src = "/Content/Math-minus-icon.png";
        var companyid = $(this).attr("rel");
        $.get("@Url.Action("CompanyEmployees","Home")?companyID=" + companyid, function (employees) {
            oTable.fnOpen(nTr, employees, 'details');
        });
    }
        });
        /* Initialize table and make first column non-sortable*/
oTable = $('#companies').dataTable({  "bJQueryUI": true,
                                        "aoColumns": [
                                        {   "bSortable": false,
                                            "bSearchable": false },
                                        null,
                                        null,
                                        null
                                ]
    });
}
<div id="demo">
    <table id="companies" class="display">
        <thead>
            <tr>
                <th></th>
                <th>ID</th>
                <th>Company Name</th>
                <th>Town</th>
            </tr>
        </thead>
    @foreach (var item in Model) {
        <tr>
            <td><img src="/Content/Math-plus-icon.png" style="cursor:pointer;" alt="expand/collapse" rel="@item.ID"/></td>
            <td>@item.ID</td>
            <td>@item.Name</td>
            <td>@item.Address</td>
        </tr>
    }
    </table>
</div>
In Third phase of this article complete ajax request will do have to add a class in Model folder whose name is
JQueryDataTableParamModel.cs ,it's code will be such as
 /// <summary>
    /// Class that encapsulates most common parameters sent by DataTables plugin
    /// </summary>
    public class JQueryDataTableParamModel
    {
        /// <summary>
        /// Request sequence number sent by DataTable, same value must be returned in response
        /// </summary>       
        public string sEcho{ get; set; }
 
        /// <summary>
        /// Text used for filtering
        /// </summary>
        public string sSearch{ get; set; }
 
        /// <summary>
        /// Number of records that should be shown in table
        /// </summary>
        public int iDisplayLength{ get; set; }
 
        /// <summary>
        /// First record that should be shown(used for paging)
        /// </summary>
        public int iDisplayStart{ get; set; }
 
        /// <summary>
        /// Number of columns in table
        /// </summary>
        public int iColumns{ get; set; }
 
        /// <summary>
        /// Number of columns that are used in sorting
        /// </summary>
        public int iSortingCols{ get; set; }
 
        /// <summary>
        /// Comma separated list of column names
        /// </summary>
        public string sColumns{ get; set; }
 
    }

After add this code in your class file go into homecontroller and add two more methods which are
below given.


public ActionResult Ajax()
        {
            return View();
        }
        /// <summary>
        /// Returns data by the criterion
        /// </summary>
        /// <param name="param">Request sent by DataTables plugin</param>
        /// <returns>JSON text used to display data
        /// <list type="">
        /// <item>sEcho - same value as in the input parameter</item>
        /// <item>iTotalRecords - Total number of unfiltered data. This value is used in the message: 
        /// "Showing *start* to *end* of *iTotalDisplayRecords* entries (filtered from *iTotalDisplayRecords* total entries)
        /// </item>
        /// <item>iTotalDisplayRecords - Total number of filtered data. This value is used in the message: 
        /// "Showing *start* to *end* of *iTotalDisplayRecords* entries (filtered from *iTotalDisplayRecords* total entries)
        /// </item>
        /// <item>aoData - Twodimensional array of values that will be displayed in table. 
        /// Number of columns must match the number of columns in table and number of rows is equal to the number of records that should be displayed in the table</item>
        /// </list>
        /// </returns>
        public ActionResult AjaxHandler(JQueryDataTableParamModel param)
        {
            var allCompanies = GetCompanies();
            IEnumerable<Company> filteredCompanies;
            //Check whether the companies should be filtered by keyword
            if (!string.IsNullOrEmpty(param.sSearch))
            {
                //Used if particulare columns are filtered 
                var nameFilter = Convert.ToString(Request["sSearch_1"]);
                var addressFilter = Convert.ToString(Request["sSearch_2"]);
                var townFilter = Convert.ToString(Request["sSearch_3"]);
 
                //Optionally check whether the columns are searchable at all 
                var isNameSearchable = Convert.ToBoolean(Request["bSearchable_1"]);
                var isAddressSearchable = Convert.ToBoolean(Request["bSearchable_2"]);
                var isTownSearchable = Convert.ToBoolean(Request["bSearchable_3"]);
 
                filteredCompanies = GetCompanies()
                   .Where(c => isNameSearchable && c.Name.ToLower().Contains(param.sSearch.ToLower())
                               ||
                               isAddressSearchable && c.Address.ToLower().Contains(param.sSearch.ToLower())
                               );
            }
            else
            {
                filteredCompanies = allCompanies;
            }
 
            var isNameSortable = Convert.ToBoolean(Request["bSortable_1"]);
            var isAddressSortable = Convert.ToBoolean(Request["bSortable_2"]);
            var isTownSortable = Convert.ToBoolean(Request["bSortable_3"]);
            var sortColumnIndex = Convert.ToInt32(Request["iSortCol_0"]);
            Func<Company, string> orderingFunction = (c => sortColumnIndex == 1 && isNameSortable ? c.Name :
                                                           sortColumnIndex == 2 && isAddressSortable ? c.Address :
                                                           "");
 
            var sortDirection = Request["sSortDir_0"]; // asc or desc
            if (sortDirection == "asc")
                filteredCompanies = filteredCompanies.OrderBy(orderingFunction);
            else
                filteredCompanies = filteredCompanies.OrderByDescending(orderingFunction);
 
            var displayedCompanies = filteredCompanies.Skip(param.iDisplayStart).Take(param.iDisplayLength);
            var result = from c in displayedCompanies select new[] { Convert.ToString(c.ID), c.Name, c.Address };
            return Json(new
            {
                sEcho = param.sEcho,
                iTotalRecords = allCompanies.Count(),
                iTotalDisplayRecords = filteredCompanies.Count(),
                aaData = result
            },
                        JsonRequestBehavior.AllowGet);
        }
        
      
    }
After adding these two methods make a new view with Ajax.cshtml name and in that source code will be
@{
    ViewBag.Title = "Ajax";
}
@section onReady
{
 
    var oTable;
    $('#companies tbody td img').live('click', function () {
    var nTr = this.parentNode.parentNode;
    if (this.src.match('details_close')) {
    /* This row is already open - close it */
    this.src = "@Url.Content("/Content/images/details_open.png")";
    oTable.fnClose(nTr);
    }
    else {
    @*/* Open this row */*@
    this.src = "@Url.Content("/Content/images/details_close.png")";
    var companyid = $(this).attr("rel");
    $.get("@Url.Action("CompanyEmployees", "Home")?companyID=" + companyid, function (employees) {
    oTable.fnOpen(nTr, employees, 'details');
    });
    }
    });
 
    
    @*/* Initialize table and make first column non-sortable*/*@
    
    
      oTable = $('#companies').dataTable({
                                    "bProcessing": true,
                                    "bServerSide": true,
                                    "sAjaxSource": 'AjaxHandler',
                                    "bJQueryUI": true,
                                    "aoColumns": [
			                                    { "bSortable": false, "bSearchable": false,
			                                        "fnRender": function (oObj) {
			                                            return '<img src="/Content/images/details_open.png" alt="expand/collapse" rel="' + oObj.aData[0] + '"/>';
			                                        } 
			                                    },
			                                  { "sName": "Name" },
    { "sName": "Address" }
    ],
    
        });
 
}
<div id="demo">
    <table id="companies" class="display">
        <thead>
            <tr>
                <th>ID</th>
                <th>Company Name</th>
                <th>Town</th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
</div>



Now Run Your Application and See Result on Click of three links and observer the difference also enjoy
your programming.
If you want to download this practical source complete get to it by below given url.
https://docs.google.com/file/d/0B-sDsBkcsM1Yc0ZRQlM5S1Z4MFE/edit?usp=sharing