Ramani Sandeep's Blog

DotNetting – Fast , Easy Way of Developing Applications

Archive for the ‘JQuery’ Category

Tips/Tricks – Hide popup when click on background part

Posted by Ramani Sandeep on March 5, 2011

Whenever we use ajax ModalPopupExtender to show popup window, we always get into the situation where we need to hide the popup based on background click. CancelControlID property helps to close popup by clicking on control specified in it. But what if we required to close it by clicking background of popup? So here is some workaround to achieve it.

The modal popup extender automatically creates a div HTML element that is used for the background. so we can hide the popup by :

  1. Fetching the background div ID and
  2. Add one event handler (click) to that div

Once we follow two steps , we can able to hide the popup on background click. I hope this is simple. so Lets start…

How to fetch div HTML element used for the background :

To get the ID of the background div, add “_backgroundElement” to the name of your ModalPopupExtender runtime ID. Why, because modal popup extender automatically creates a div HTML element with ID which contains :

ModalPopupExtender ID + “_backgroundElement”

i.e. “ctl00_mpeTest_backgroundElement” , here mpeTest is our ModalPopupExtender’s ID

Now our task to fetch that div ID, here is the jQuery code that can help us to achieve it :

   var modalWindow = '<%= mpeTest.ClientID %>';
   var backgroundElement = $get(modalWindow + '_backgroundElement');

Here ‘mpeTest‘ is the ID of ModalPopupExtender.

Add event handler to the background div :

Here is the code to add click event to backgroundElement :

  var modalWindow = '<%= mpeTest.ClientID %>';
  var backgroundElement = $get(modalWindow + '_backgroundElement');
  $addHandler(backgroundElement, 'click', hideModalPopupViaClient);

hideModalPopupViaClient‘ is the javascript function name which will be called when we click on background of the popup window.

Example :

Here is the complete listing with all part of code along with css, javascript and ASPX page code with controls used in it.

Listing #1 : style sheet classes used for modalpopup and its background


 <style>
        .modalBackground
        {
            background-color: gray;
            filter: alpha(opacity=70);
            -moz-opacity: 0.70;
            opacity: 0.70;
        }
        .modalPopup
        {
            background-color: #fff;
            border-width: 1px;
            border-style: solid;
            border-color: #000;
            width: auto;
            height: auto;
            text-align: center;
        }
    </style>

Listing #2 : jQuery script specify how we can show/hide modalpopup


 <script src="js/jquery-1.4.2.min.js" type="text/javascript"></script>

    <script type="text/javascript">
        function ShowPopup() {

            //show modal popup window
            var modalWindow = '<%= mpeTest.ClientID %>';
            $find(modalWindow).show();

            //add event handler to hide the modal popup when user click background of the popup window
            var backgroundElement = $get(modalWindow + '_backgroundElement');
            if (backgroundElement) $addHandler(backgroundElement, 'click', hideModalPopupViaClient);

            return false;
        }

        function hideModalPopupViaClient() {

            //hide modal popup window
            var modalPopupBehavior = $find('<%= mpeTest.ClientID %>');

            if (modalPopupBehavior) {
                modalPopupBehavior.hide();
            }
        }
    </script>

I have given enough explaination in above section , so no need to describe it again.

Listing #3 : ASPX page content , where I have taken ModalPopupExtender and set few property of it to let it work.


<ajaxtoolkit:ToolkitScriptManager ID="scriptManager" runat="server"></ajaxtoolkit:ToolkitScriptManager>

<asp:ImageButton ID="imgBtnTour" runat="server" ImageUrl="~/Images/movie_icon.jpg"
            Width="80" OnClientClick="return ShowPopup();" />

<asp:Button runat="server" ID="btnHiddenPopUp" Style="display: none" />

<ajaxtoolkit:ModalPopupExtender ID="mpeTest" runat="server" TargetControlID="btnHiddenPopUp"
            PopupControlID="panSaving" BackgroundCssClass="modalBackground" DropShadow="true"
            RepositionMode="RepositionOnWindowResize" CancelControlID="imgClose" />

<asp:Panel runat="server" CssClass="modalPopup" ID="panSaving" Style="display: none">
    	<table cellpadding="0" cellspacing="0" border="0">
         	<tr>
                    <td style="padding: 5px 5px 0px 0px" align="right">
                        <asp:Image ID="imgClose" runat="server" ImageUrl="~/Images/close.png" />
                    </td>
                </tr>
                <tr>
                    <td>
                        <h1>
                            This is modal popup message</h1>
                    </td>
                </tr>
            </table>
</asp:Panel>

Thats it !!!

Hope this will help !!!

Jay Ganesh

Posted in Ajax Toolkit, CodeProject, JQuery, Tips and Tricks | Tagged: , , , , | 1 Comment »

Check File type at client side – jQuery

Posted by Ramani Sandeep on February 4, 2011

Whenever we use fileupload control on web pages , the common requirement is to validate its file type and size.

we usually find it difficult to validate file size on client side rather than at server side. As of now there is no alternative script found that can achieve this. There are certain alternatives to achieve above validation on client side but that are not browser compatible & as security level changes in browser it stop functioning, so we still not at that level of trust that we can check file size at client side using jQuery/javascript.

Although it is possible to validate filetype using jquery/javascript and i m looking to do some coding for you to achieve the same. i hope this will help some developers to validate file type at client side rather than checking it on server.

Here is the javascript code that achieve above functionality :


 <script src="Js/jquery-1.4.2.min.js" type="text/javascript"></script>

    <script type="text/javascript" language="javascript">

        function FileTypeValidate() {

            //get filepath from fileupload control on the page
            var fileUpload = $('#<%=FileUpload1.ClientID %>').val();

            //extracting part of the filename from dot
            var extension = fileUpload.substring(fileUpload.lastIndexOf('.'));

            //valid file type - static
            var ValidFileType = ".jpg , .png , .bmp";
            //or fetch it from config file for flexibility ,
	    //we can save valid file type list in web.config also & fetch it during validation process
            var ValidFileTypeConfig = '<%=ConfigurationManager.AppSettings["ValidFileType"].ToString() %>';

            //check whether user has selected file or not
            if (fileUpload.length > 0) {

                //check file is of valid type or not
                if (ValidFileType.toLowerCase().indexOf(extension) < 0) {
                    alert("please select valid file type...");
                }
                else {
                    alert("file type is valid...");
                    return true;
                }
            }
            else {
                alert("please select file for upload...");
            }
            return false;
        }
    </script>

Above code explain itself a lot so no need to discuss further on it.

Here is the html markup that shows controls on the page :


    <form id="form1" runat="server">
     <div>
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <asp:Button ID="Button1" runat="server" Text="Upload" OnClientClick="return FileTypeValidate();" />
     </div>
    </form>

This is very simple but very common scenario for the web applications & very effective if managed properly…

Thats it, hope this will help !!!

Jay Ganesh

Posted in CodeProject, JavaScript, JQuery | Tagged: , , , | 1 Comment »

Sorting Table Columns with jQuery

Posted by Ramani Sandeep on September 2, 2010

Background

I always heard about sorting table data & read lots of article that explain how to achieve it using jquery. You will also find lots of plugins available for sorting table data like Table sorter, Flexigrid , jqGrid and many more. Along with sorting feature it also support many more features like paging, resizable columns, cool themes, search and many more… But I feel that there must be one more feature in this library to sort table columns so that user will have full flexibility by playing with table arrangement along with column data. It might be possible that some of the library support this features or if not then planning to add it in their upcoming releases..

Sample Code

This code consist of GridView which shows Employee Name as Column along with some data. Now when user press sort button column will be sorted in ascending order along with data.

Here I have tried to achieve this features using some of the jQuery code without need of any library. Only thing we need here is jQuery library.

Step 1 : Add jQuery file Reference inside the tag of the page

<script src="Js/jquery-1.4.2.js" type="text/javascript"></script>

Step 2 : Next we need to drag and drop gridview on the page & set AutoGenerateColumns property to false. Specify the ID of the grid “gvEmployees”.

<asp:GridView ID="gvEmployees" runat="server" AutoGenerateColumns="false" Width="500">
   <Columns>
      <asp:BoundField DataField="Sandeep" HeaderText="Sandeep" />
      <asp:BoundField DataField="Nishar" HeaderText="Nishar" />
      <asp:BoundField DataField="Dharmik" HeaderText="Dharmik" />
      <asp:BoundField DataField="Ravi" HeaderText="Ravi" />
      <asp:BoundField DataField="Jigish" HeaderText="Jigish" />
      <asp:BoundField DataField="Kapil" HeaderText="Kapil" />
   </Columns>
</asp:GridView>

Step 3 : Drag and drop one button on the page and give its ID=”btnSortColumn” and Text=”Sort Column”.

<asp:Button ID="btnSortColumn" runat="server" Text="Sort Column" />

Step 4 : write jQuery script for the button click event, which will sort table column along with data.

       $('#btnSortColumn').click(function() {

            //Get all the rows of employee grid
            var rows = $('#gvEmployees tr');

            //Start sorting column along with data
            rows.eq(0).find('th').sort(function(a, b) {

                return $.text([a]) > $.text([b]) ? 1 : -1;

            }).each(function(new_Index) {

                //Original Index
                var original_Index = $(this).index();

                //Reorder Header Text
                rows.each(function() {
                    var th = $(this).find('th');
                    if (original_Index !== new_Index)
                        th.eq(original_Index).insertAfter(th.eq(new_Index));
                });

                //Reorder Column Data
                rows.each(function() {
                    var td = $(this).find('td');
                    if (original_Index !== new_Index)
                        td.eq(original_Index).insertAfter(td.eq(new_Index));
                });

            });
            return false;
        });

Code itself explain lots of things,

Here ‘rows’ variable contain collection of Employee row. Next we find out the column name using header tag (th) and call the sort function of javascript to call the sorting mechanism.

rows.eq(0).find('th').sort(function(a, b)
{
    return $.text([a]) > $.text([b]) ? 1 : -1;
})

When such a function is passed into array.sort(), the array elements are sorted based on the relationship between each pair of elements “a” and “b” and the function’s return value. The three possible return numbers are: <0 (less than 0), 0, or >0 (greater than 0):

  • Less than 0: Sort “a” to be a lower index than “b”
  • Zero: “a” and “b” should be considered equal, and no sorting performed
  • Greater than 0: Sort “b” to be a lower index than “a”

To sort an array numerically and ascending for example, the body of your function would look like this:

function sortfunction(a, b){
return (a - b) //causes an array to be sorted numerically and ascending
}

th.eq(original_Index).insertAfter(th.eq(new_Index));

Will insert every table header element ( th ) from original place to new place.

td.eq(original_Index).insertAfter(td.eq(new_Index));

Will insert every table data element ( td ) from original place to new place.

Step 5 : Now we have done with aspx page coding , but what about data filling logic. here it goes. Call data biding function of the gridview in Page Load event.

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGridData();
        }
    }

    private void BindGridData()
    {
        DataTable table = new DataTable();
        table.Columns.Add("Sandeep");
        table.Columns.Add("Nishar");
        table.Columns.Add("Dharmik");
        table.Columns.Add("Ravi");
        table.Columns.Add("Jigish");
        table.Columns.Add("Kapil");
        table.Rows.Add("20", "25", "45", "33", "22", "12");
        table.Rows.Add("40", "15", "15", "13", "12", "40");

        gvEmployees.DataSource = table;
        gvEmployees.DataBind();
    }

Here i have created dynamic datatable & filled some data rather than making Database connection & fetch data. but you can do what ever you want to bind grid.

Step 6 : Everything is setup now just press F5 & see the output of the page.

Before Sorting Column

After Sorting Column

Browser Support

I have tested this code on Firefox 3.6.8 & IE 8. you can also test it on any browser, i am sure that this code will run on all the latest browser.

Hope this will help !!!

Jay Ganesh

Reference

http://www.javascriptkit.com/javatutors/arraysort.shtml
http://api.jquery.com/insertAfter/

Shout it

kick it on DotNetKicks.com

Posted in CodeProject, JQuery | Tagged: , , , | 11 Comments »

7 jQuery Articles on Script Junkie

Posted by Ramani Sandeep on June 18, 2010

Today When i was reading my twits, I found very good reference link from scott guthrie about jQuery which has been written by Christian on Script Junkie Website.

Christian has written following articles :

I have gone thru these articles & i found it very interesting and useful.

Hope this helps !!!

Jay Ganesh (.j.)

Posted in JQuery | Tagged: , , , , , , , | 2 Comments »

DNJ – Dot Net jQuery

Posted by Ramani Sandeep on April 28, 2010

DNJ is Open Source framework to make use of jQuery in an ASP.NET application easier.

This article is a quick guide to some features of the DNJ framework. DNJ is an Open Source framework that helps using jQuery with ASP.NET applications. It provide helper functions, an AJAX extender, a transparent RPC, and an implementation of the jQuery UI components as ASP.NET web controls.

View full Article : http://www.codeproject.com/KB/aspnet/dotnetjquery.aspx

Read more : http://dnj.eurekaa.org/

Posted in ASP.NET 3.5, JQuery | Tagged: | 2 Comments »

Click and Retrieve the Value of a GridView Cell using jQuery

Posted by Ramani Sandeep on April 25, 2010

This article demonstrates how to click and retrieve data from a GridView cell.

This article is a sample chapter from Suprotim Agarwal EBook called 51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls.

The chapter has been modified a little to publish it as an article.

click here to read more 

Posted in ASP.NET 3.5, JQuery | Tagged: , | 1 Comment »

Lazy Loading jQuery Collapsible Panel in ASP.Net Using JSON by Satheesh Babu

Posted by Ramani Sandeep on April 14, 2010

Recently I have read very good article on Lazy Loading Collapsible panel in ASP.NET Using JSON.

Satheesh babu has written a very good article on this. I hope it can help you to increase your jQuery skill.

In collapsible panel we fully load the contents when the page is initially rendered to the client. Hence, clicking the arrow buttons on the panel will just expand and collapse the contents. This will make the page heavy when there are large amount of data on different panels on the page. It will be better and light weight when we actually load the contents of the panels only when the user clicks the expand arrow button, a lazy loading or loading on-demand.

Read full article : here

Hope this will helps !!!

Jay Ganesh

Posted in ASP.NET 3.5, JQuery | Tagged: , , , | Leave a Comment »

Yahoo! News Rotator using jQuery, CSS, JSON, and ASP.NET

Posted by Ramani Sandeep on March 31, 2010

This Yahoo! news rotator control gives us the possibility of displaying several main news stories within the same area of a web page. News is taken apart to several pages in order to place them in a specified area. Each page also contains a couple of news items.

The control uses jQuery to:

  •     Send a jQuery AJAX request to a web server to get news in JSON format
  •     Bind data (news in the form of JSON) to HTML controls
  •     Set the control style after data binding
  •     Navigate between news
  •     Interact with user
  •     Change and set styles
  •     Do JavaScript effects

The news rotator control uses ASP.NET to gather news from a news storage (for example, database, XML file, RSS, …), to cast news into a custom type (NewsItem), then convert a collection of NewsItem objects to JSON format and send it to the client as a news rotator datasource.

Read more

Hope this helps !!!

Jay Ganesh

Posted in ASP.NET, JQuery | Tagged: , | Leave a Comment »

Using jqGrid’s search toolbar with multiple filters in ASP.NET MVC

Posted by Ramani Sandeep on March 23, 2010

This article describes how to use jqGrid’s search toolbar with multiple filters in ASP.NET MVC.

Introduction

Very often, we have a requirement to display data in tabular form and manipulate it. In classic ASP.NET, built-in controls are available. It’s always better to use custom scripts to solve this problem in ASP.NET MVC. jqGrid is one of such solutions.

Background

jqGrid is a plugin for jQuery, which allows you to display data in tabular form with greater functionality. Its features include:

  1. Supports tables within tables
  2. Supports data editing
  3. Supports tree-like structure to display data
  4. Supports themes on the jQuery UI
  5. Records searching, filtering of each column, sorting by columns, page navigation, etc.

You can read full article with example here.

Hope this will help !

Jay Ganesh

Shout it

Posted in ASP.NET MVC, JQuery | Tagged: , | 2 Comments »

Start Learning jQuery

Posted by Ramani Sandeep on March 19, 2010

Powerful Web applications require powerful client capabilities. Web developers have traditionally relied upon JavaScript to deliver that power. However, raw JavaScript has its limitations, some of which can be addressed via libraries and object orientation.

There are many JavaScript libraries available, but after a while they all look the same. If you can’t decide where to begin, I would suggest you start right here—with jQuery.

Explore Rich Client Scripting With jQuery, Part 1

Key topics covered in this article are selectors, filters, wrapped sets, and chained functions.

Read more

Explore Rich Client Scripting With jQuery, Part 2

Key topics covered in this article are eventing model, visual effects, caching, and AJAX capabilities.

Read more

Build Rich User Interfaces with jQuery

In this article, I’ll build modal and modeless dialog boxes in jQuery and explain how to post data from them to the Web server.

Like many other libraries and frameworks, the jQuery library doesn’t use the browser’s pop-up windows to implement dialog boxes. Instead, jQuery relies on script code to pop up a fragment of the Document Object Model (DOM) and dismiss it when the user confirms the content or the abort operation is performed. Because the displayed content is part of the DOM of the current page, there are no postback problems and, more importantly, AJAX capabilities can be implemented.

Read more

Hope this will help

Jay Ganesh

Shout it

Posted in JQuery | Tagged: , , | 1 Comment »

 
Follow

Get every new post delivered to your Inbox.

Join 37 other followers