Showing posts with label JQuery and CSS. Show all posts
Showing posts with label JQuery and CSS. Show all posts

Tuesday, 18 February 2014

How to open a new tab On click of a hyper-linked column in Telerik Razor Grid

Today i got a requirement to open a external URL in a tab when the linked column is clicked.
This  can be achieved by simply adding the client template/ template to the linked column.

1) Using Template Attribute in the Telerik Grid
column.Bound(a => a.Website)
      .Template(@<text><a href="@Url.Content(item.Website)" target="_blank">@item.Website</a></text>)
      .HeaderTemplate(
        @<text>
    <a href="javascript:void(0)" class="t-link" orderby="Website">Website</a>
@Html.TextBoxFor(m => m.Filter.Website)         
</text>);

2) Using Client Template Attribute in the Telerik Grid


column.Bound(a => a.Website)
    .ClientTemplate("<a href='<#= Website #>' target='_blank'><#= Website #></a>")
    .HeaderTemplate(
        @<text>
    <a href="javascript:void(0)" class="t-link" orderby="Website">Website</a>
@Html.TextBoxFor(m => m.Filter.Website)         
</text>);

Output:


But the really annoying is that when you click the link it is throwing error  as
 "The resource you are looking for has been removed, had its name changed, or is temporarily unavailable"



This is because the IIS is unable to resolve the path.

Solution to the above issue:

The above issue can be fixed by a simple trick, just you need to append the http:// to the website in the client template or in the template attribute. See the code below:

column.Bound(a => a.Website)
      .Template(@<text><a href="@Url.Content("http://"+item.Website)" target="_blank">@item.Website</a></text>)
      .HeaderTemplate(
        @<text>
    <a href="javascript:void(0)" class="t-link" orderby="Website">Website</a>
@Html.TextBoxFor(m => m.Filter.Website)         
</text>);

Note: Similarly if it is a mail ID column then, use mailto: as the prefix.

Thats it, Enjoy!

Monday, 23 September 2013

How to Insert space before capital letters using Jquery

Assume you have a string "HelloWorld" and you need to show as "Hello World". How you can achieve it using Jquery.

It can be done in a very simpler way as below:

"Your string".replace( /([a-z])([A-Z])/g, "$1 $2")

so here it will be "HelloWorld".replace( /([a-z])([A-Z])/g, "$1 $2") will produce "Hello World"

Enjoy!

Friday, 14 June 2013

How to prevent the multiple submit of record in ASP.Net MVC using JQuery

There are various methods are available to do that one, it can be done using JQuery, using sessions or Filters.


Method -1 ( Using JQuery Approach)
 $('form').submit(function () {
        if ($(this).find('.input-validation-error').length == 0) {
            $(this).find(':submit').attr('disabled''disabled');
        }
    });

This is the simplest method to prevent the multiple submission of the record in MVC and even it works on JQuery Unobstructive validations.

Happy Coding!

Friday, 24 May 2013

Jquery Method to Check the File upload control Empty or not, File Size and File Type(e.g. JPG,BMP,PDF)


Html:
<input type="file" id="file" name="file" />
<span id="valFile" class=""></span> // span for showing error message.

CSS:


.field-validation-error {
    color: #f00;
}

.field-validation-valid {
    display: none;
}

.input-validation-error {
    border: 1px solid #f00;
    background-color: #fee;
}


JQuery Snippet:
$(document).ready(function( )
{

//Changing the Error message of the File Upload and checking the File size and File type.
        $("#file").change(function () {

            $("#valFile").html("Please select file."); // Default Error Message
         
            var fileExtension = ['jpeg', 'jpg', 'png', 'gif', 'bmp', 'doc', 'docx', 'pdf'];

            if ($(this).val() != "") { //checking wheather the file uploader is empty or not
             
                //Checking the File type
                if ($.inArray($(this).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
                    $(this).addClass("input-validation-error").removeClass("valid");
                    $("#valFile").addClass("field-validation-error").removeClass("field-validation-valid")
                        .html("Invalid Filetype(only image files/doc/docx/pdf)");
                }
                else {
                    $(this).removeClass("input-validation-error").addClass("valid");
                    $("#valFile").removeClass("field-validation-error").addClass("field-validation-valid");

                    if ((this.files[0].size > 4194304) && ($(this).val() != '')) {
                        $(this).addClass("input-validation-error").removeClass("valid");
                        $("#valFile").addClass("field-validation-error").removeClass("field-validation-valid")
                            .html("File size exceeded 4MB");
                    }
                }
            } else {
                $(this).addClass("input-validation-error").removeClass("valid");
                $("#valFile").addClass("field-validation-error").removeClass("field-validation-valid");
            }
        });

});

Happy Coding!

Friday, 17 May 2013

How to make a textbox to accept only integers as Input.

Html Page:
 <input type="text" name="age" id="txtAge" />&nbsp;<span id="errormsg"></span>

JQuery Snippet for the above TextBox:

Method-1:
$(document).ready(function () {
  //called when key is pressed in textbox
  $("#txtAge").keypress(function (e) {
     //if the letter is not digit then display error and don't type anything
     if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
        //display error message
        $("#errormsg").html("Digits Only").show().fadeOut("slow");
               return false;
    }
   });
});

Method-2:
$(document).ready(function () {
    $("#txtAge").keydown(function (e) {
        if (e.shiftKey) e.preventDefault();
        else {
            var nKeyCode = e.keyCode;
            //Ignore Backspace (Keycode=8), Tab keys(Keycode=9)  & Delete(Keycode=46)
         if (nKeyCode == 8 || nKeyCode == 9 || nKeyCode == 46) return;
            if (nKeyCode < 95) {
                if (nKeyCode < 48 || nKeyCode > 57) e.preventDefault();
            } else {
                if (nKeyCode < 96 || nKeyCode > 105) e.preventDefault();
            }
        }
    });
});

Enjoy!

Wednesday, 24 April 2013

Searching Records from the Kendo Grid by Date given in the Search Box.

While working on a project I came to an issue in kendo grid i.e to search the Grid records using Date.
Say , I had an accounts list from a bank in which lots of data are displayed including A/C opening date, Last log-in, Last transaction, Last Unsuccessful Log-in and there is a search box that finds the records when the date is given in the search box. But to my dismay it doesn't works for me, after spending a valuable of 1 day of my work , I had got the success.

So here is the image below:





The Code to make your grid work for dates filtration or searching:

In the web page(.html / .cshtml / .jsp etc)
<div id="grid"></div>

Script:
<script type="text/javascript">


$(document).ready(function () {
       initGrid();
      
/// This function is called when you start typing in the search textbox. Here Id of search textbox is #search.
    $('#search').keyup(function () {
        clearTimeout($.data(this, 'timer'));
        var wait = setTimeout(searchDataSource, 500);
        $(this).data('timer', wait);
    });

});



 function searchDataSource() {
        var query = $("#search").val();
        var $filter = [
                       { field: "AccOpenDate", operator: "eq", value: new Date(query) },
                       { field: "LastLogin", operator: "eq", value: new Date(query) },
                       { field: "LastTrans", operator: "eq", value: new Date(query) },
                       { field: "FaliureLogin", operator: "eq", value: new Date(query) }
        ];

        if (query.length > 2)  // search only when the no. of character typed is greater than 2
        {
            grid.data("kendoGrid").dataSource.filter({
                logic: "or",
                filters: $filter
            });

        } else if (query.length == 0)
            grid.data("kendoGrid").dataSource.filter([]);
    }


 function initGrid() {
        grid = $("#grid").kendoGrid({
            dataSource: {
                transport: { read: "/Bank/accounts" },
                schema: { data: "Data", total: "Total" },
                pageSize: 30,
                serverPaging: false,
                serverFiltering: false,
                serverSorting: false
            },
            height: gridHeight,
            change: function () {
                var selectedRows = this.select();
                selectedElement = this.dataItem(selectedRows[0]);
                showActionPane(selectedElement.Name != null && selectedElement.Name != "");
            },
            selectable: "single",
            filterable: true,
            sortable: true,
            pageable: true,
            resizable: true,
            columns: [

                { field: "Name", title: "Name", width: 60, template: '<a href="/Account/Details/#=Id#">#=Name#</a>' },
                { field: "Status", title: "Status", width: 50 },
                { field: "AccountType", title: "Account Type", width: 80 },
                { field: "AccOpenDate", title: "A/c Open Date", width: 50, template: '#=(AccOpenDate==null)?"":kendo.toString(kendo.parseDate(AccOpenDate,"0:MM/dd/yyyy"),"MM/dd/yyyy") #', filterable: true, format: "{0:M/d/yyyy}", type: "date" },
                { field: "LastLogin", title: "Last Login", width: 50, template: '#=(LastLogin==null)?"":kendo.toString(kendo.parseDate(LastLogin,"0:MM/dd/yyyy"),"MM/dd/yyyy") #', filterable: false, format: "{0:M/d/yyyy}", type: "date" },
                { field: "LastTrans", title: "Last Transaction", width: 50, template: '#=(LastTrans==null)?"":kendo.toString(kendo.parseDate(LastTrans,"0:MM/dd/yyyy"),"MM/dd/yyyy") #', filterable: false, format: "{0:M/d/yyyy}", type: "date" },
                { field: "FaliureLogin", title: "Unsuccessful Login", width: 50, template: '#=(FaliureLogin==null)?"":kendo.toString(kendo.parseDate(FaliureLogin,"0:MM/dd/yyyy"),"MM/dd/yyyy") #', filterable: false, format: "{0:M/d/yyyy}", type: "date" }
            ]
        });
    }

output:
Search records by Date through Search Textbox text:  ( here searching the record occurs on all the columns)



Search records by Date through filter Button: ( here searching the record which has opened on 04/04/2013. So two records where as in the above it is searching all the columns having 04/04/2013. so three records. 


Tuesday, 23 April 2013

How to count the number of check-box checked on a particular condition from a table using Jquery

Scenario: Assume that a table has data from a cricket team with details such as ID , Name, Role , Age ,City, Average. SO you need to calculate how many bowlers you have selected from the table, total no. of players selected and their average age.


Similarly, if batsman age or count is required then simply change the value of Contains to "Batsman" from the above code.

Happy Coding!

How to check all the check box when All check-box is checked and uncheck All check-box, if one of the check-box from the group is unchecked


       
<form name="frmChkForm" id="frmChkForm">
<input type="checkbox" name="chkcc9" id="chkAll">Check Me
<input type="checkbox" name="Bowler" class="chkGroup">Bowler
<input type="checkbox" name="Batsman" class="chkGroup">Batsman
<input type="checkbox" name="AllRounder" class="chkGroup">AllRounder
</form>

$("#chkAll").click(function() {
   $(".chkGroup").attr("checked", this.checked);
});

With added functionality to ensure the check all checkbox gets checked/dechecked if all individual checkboxes are checked:

$(".chkGroup").click(function() {
  $("#chkAll")[0].checked = $(".chkGroup:checked").length == $(".chkGroup").length;
});


Happy Coding!

Blank out a form/ reset a form with jQuery


First method:
<form id="form">
<input type="text" value="Here is some data" id="data" />
<input type="button" value="Clear Input" id="button" />
</form>

$(function(){
 
    $('#button').click(function(){
       $(':input','#form').not(':button, :submit, :reset, :hidden').val('').removeAttr('checked,selected');
    });
});

Second method:
function clearForms()
{
  var i;
  for (i = 0; (i < document.forms.length); i++) {
    document.forms[i].reset();
  }
}

Happy Coding!

Monday, 22 April 2013

Ajax method of calling Action method of a controller:

I need to call a action method in order to save the uploaded image file using Jquery or the Ajax method. So below is the code for it.


$.ajax({
           url:
"/Image/UploadTest", // Image is the controller & UploadTest is Action Method

           type: "POST",
           data: $("#frmTest"
).serialize(),   // Here provide the form Id
           async:
false,
           cache:
false,                      // Don't keep the cache
           beforeSend:
function () {  // This Executes before calling the Ajax Request
                  $(
"#uploadProgress").show();   // Here I am showing Uploader image
              },
           complete:
function () {
                  $(
"#uploadProgress").html("Upload completed"); 

                // Executes on Ajax request complete
              },
          success:
function (msg) {

                 
if (msg == "ok")
                      $(
"#uploadProgress").hide();  // hiding the uploader image on successs
                 
else
                      alert(
"Error while uploading");

              }
          });

Kendo Grid with Search Functionality


<!DOCTYPE html>
<html>
<head>
<link href="http://cdn.kendostatic.com/2012.3.1114/styles/kendo.common.min.css" rel="stylesheet" type="text/css" />
<link href="http://cdn.kendostatic.com/2012.3.1114/styles/kendo.rtl.min.css" rel="stylesheet" type="text/css" />
<link href="http://cdn.kendostatic.com/2012.3.1114/styles/kendo.default.min.css" rel="stylesheet" type="text/css" />
<link href="http://cdn.kendostatic.com/2012.3.1114/styles/kendo.dataviz.min.css" rel="stylesheet" type="text/css" />
<link href="http://cdn.kendostatic.com/2012.3.1114/styles/kendo.dataviz.default.min.css" rel="stylesheet" type="text/css" />
<link href="http://cdn.kendostatic.com/2012.3.1114/styles/kendo.mobile.all.min.css" rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="http://cdn.kendostatic.com/2012.3.1114/js/kendo.all.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
  <div id="grid"></div>
</body>
</html>
<script type=”text/javascript”>
  $("#grid").kendoGrid({
  dataSource:[ {
      foo: "Foo 1",
      bar: "Bar 1"
    } , {
      foo: "Foo 2",
      bar: "Bar 2"
    }
  ]
});
var grid = $("#grid").data("kendoGrid");
$("<tr><th class='k-header' data-field='foo'><input /></th><th data-field='bar' class='k-header' ><input /></th></tr>").appendTo($("#grid thead")).find("input").keyup(function() {
    grid.dataSource.filter({
    operator: "contains",
    value: $(this).val(),
    field: $(this).parent("th").data("field")
  });
  });
</script>
Happy Coding!

Monday, 15 April 2013

Kendo UI Grid Page size showing NaN of NaN.

In kendo grid, sometimes you will get the page size of the grid as NaN  of NaN.


The reason behind it was that the kendo grid is telling that the page size is not define, although you have define it and on clicking the page size or selected page the NaN of NaN goes.

Solution:
To fix the above solution , just redefine the page-size in the dataSource and the above issue will go.



Happy Coding!

Kendo Grid- Binding the JSON Data after getting response from the Ajax Call.

In Kendo UI while you are getting the data as a JSON object  and you want to bind into a grid, so follow the method below :
<script type= "text/javascript">
$(document).ready(
function( )
{
     InitializeGrid( );
 }

 function InitializeGrid() {
        $.ajax({
            async: false,
            type: "POST",
            url: "/Employee/GetEmployeeByFilter",
            data: $('#frmSearch').serialize(),
        }).success(function (result) {
            grid = $("#grid").kendoGrid({
                dataSource: { data: result.Data, total: result.Total, pageSize: 30 },
                schema: { data: "Data", total: "Total" },
                type: "POST",
                serverPaging: false,
                serverFiltering: false,
                serverSorting: false,
                height: gridHeight,
                toolbar: kendo.template($("#template").html()),
                change: function () {
                    var selectedRows = this.select();
                    selectedElement = this.dataItem(selectedRows[0]);
                },
                selectable: "single",
                filterable: true,
                sortable: true,
                pageable: true,
                resizable: true,
                columns: [
                    { field: "Name", title: "Name", width: 65 },
                    { field: "Emp_No", title: "Emp No", type: 'string', width: 62 },
                    { field: "Salary", title: "Salary", type: 'string', width: 78 },
                  ]
            });
        });
    }
</script>

View:

<div id="EmployeeReport">
    <h1 id="employeeReport">EmployeeReport</h1>
    <div id="grid"></div>
</div>

In the controller side:

   public ActionResult GetEmployeeByFilter( Receive the Parameters from the client side )
        {
                // Do the processing......
                return Json(new { Data =List of object you want to Pass to client side,
                                           Total = List's Count }, JsonRequestBehavior.AllowGet);
        }

Happy coding!


Tuesday, 9 April 2013

Kendo UI Sorting Date field in a grid having empty spaces and dates

Today i came to an issue that the date field are not sorted properly in the kendo grid if it has empty or Null spaces in it. the sorting occurs fine for descending order but fails when it is ascending order.

To fix the above issue a small trick will work for it. Just use this line of code in the grid filtration.

{field: "DateJoined", title: "Deployed", width: 50, template: '#=(DateJoined==null)?"":kendo.toString(kendo.parseDate(DateJoined,"MM/dd/yyyy"),"MM/dd/yyyy") #', format: "{0:M/d/yyyy}", type: "date" },

Happy coding!

How to fix the non-breaking of a sentence in HTML which has a hyphen(-) in it ?

Some times if you provide data inside a span or a column as : abcdef-test@gmail.com, you will notice that in IE it will be displayed as :
abcedf-
test@gmail.com
To fix the above issue, i will provide you two solutions.


Solution -1: Use <nobr> Tag

You can use <nobr> tag to represent your data as <nobr>abcdef-test@gmail.com</nobr>



Solution -2: Use CSS

You can use CSS to fix the above issue as:


<span style="white-space: nowrap;">abcdef-test@gmail.com</span>


Cheers!

Monday, 18 February 2013

Center an element on the screen using jQuery



    this.css("position","absolute");
    this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
    this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
    return this;
}

 This is how you use it:  $('#window').center();

The above method will show the control @ center of the Window.

Sunday, 17 February 2013

How to resize a website dynamically as per the window size

Today I got some requirement to re-size the some website that should doesn't have scroll bar and need to adjust dynamically as per the window size.

To do that you need to do it JQuery or CSS. I am posting here how you will do it in JQuery.

Just put this script in the page which you want to adjust its size.

<script type="text/javascript">
    $(document).ready(function () {
        Resize();
    });
    

 $(window).resize(function () { Resize(); location.reload(true); }); // when the window get re-sized
   
    function Resize() {
        var height = window.innerHeight ? window.innerHeight : $(window).height();
        height = height - 96; // Height of the Logo and the Footer is 96px so it is deducted.
        $("#leftNav").height(height);
    }
</script>


Here i am concerned about the height. I you want to resize with width also you can use $(window).width().

Note: Be cautious if you are still want to work the code in IE7 the do remember the following things, you need to deduct the view port


    if (jQuery.browser.msie) {
        if(parseInt(jQuery.browser.version) == 7) {
            viewportHeight -= 3;
        }
    }

    if($('#leftNav').height() > viewportHeight) {
        $('#leftNav').height($('#leftNav').height() - viewportHeight);
    }

    if($('#leftNav').height() < viewportHeight) {
        $('#leftNav').height(viewportHeight - $('#leftNav').height());
    }