Showing posts with label ASP.NET. Show all posts
Showing posts with label ASP.NET. Show all posts

Tuesday, May 13, 2014

jQuery - Load ASP.Net User Control Dynamically

In this post, find jQuery code to load ASP.NET user control dynamically using jQuery and ajax together. To achieve this, we need to declare a WebMethod on server side which actually adds the user control to a Page class object. And using jQuery and Ajax, call this WebMethod and append the respond to any DOM element. The response will be content of User Control.

Below ASP.NET code, declares a WebMethod named "LoadUserControl". This method creates an object of Page class and then add the UserControl to Page class object. And then using Server.Execute method executes the page on the server in the current directory and receives the output from the page through the StringWriter object writer. It writes the HTML stream received from writer to the HTTP output stream.
[WebMethod]
public static string LoadUserControl()
{
  using (Page objPage = new Page())
  {
     UserControl uControl = 
                         (UserControl)objPage.LoadControl("TestUC.ascx");
     objPage.Controls.Add(uControl);
     using (StringWriter sWriter = new StringWriter())
     {
         HttpContext.Current.Server.Execute(objPage, sWriter, false);
         return sWriter.ToString();
     }
  }
}
And below is jQuery code to make an ajax request on button click and then append the response received from WebMethod to any DOM element to render the content of User Control. Also read "Execute/Run multiple Ajax request simultaneously"
$(document).ready(function () {
    $("#btnLoadControl").on("click", function (e) {
        $.ajax({
            type: "POST",
            url: "Default.aspx/LoadUserControl",
            data: "",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (r) {
                $("#dvUControl").append(r.d);
            }
        });
        e.preventDefault();
    });
});
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Tuesday, April 15, 2014

Export table to Excel using jQuery in IE

Previously I had posted about Export table data to Excel using jQuery but that solution doesn't work in IE. And many of us are looking for solution to this problem. If you are using ASP.NET, then by end of this post you will have the solution.

To make it work for IE with ASP.NET, we need to append header in Response object and then allow downloading of file. This can't be done only on client side for IE. So the idea is to pass the table data along with its structure to ASP.NET server side code and then using server side code, allow downloading of file. But before passing the data to server, escape the HTML tags to handle "A potentially dangerous Request. Form value was detected from the client" exception.

Below jQuery code attaches click handler to button and escapes the data and assign it to a hidden field. The same hidden field will be accessed at server side to get the escaped table structure.
$(document).ready(function () {
    $("#btnExport").on('click', function (e) {
          var tblHTML = $("#dvData").html();
          tblHTML = escape(tblHTML);
          $('#hdnData').val(tblHTML);
   });
});
And below is ASP.NET server side button click code, which adds header to Response object and defines the content type to "application/excel". And then writes the data.
protected void btnExport_Click(object sender, EventArgs e)
 {
   string data = hdnData.Value;
   data = HttpUtility.UrlDecode(data);
   Response.Clear();
   Response.AddHeader("content-disposition", "attachment;filename=Data.xls");
   Response.Charset = "";
   Response.ContentType = "application/excel";
   HttpContext.Current.Response.Write(data);
   HttpContext.Current.Response.Flush();
   HttpContext.Current.Response.End();
}
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Tuesday, March 25, 2014

jQuery: Convert ASP.NET GridView Data into CSV

In this post, find jQuery code to convert ASP.NET GridView data into CSV format which is sometimes quite useful for exporting purpose. This can be also be done using server side code but that involves extra overhead "postback".

ASP.NET GridView control is rendered in table > th > tr > td format. The columns names are placed in th tag and all the data goes into various td tags. Also refer ebook on ASP.NET GridView & jQuery Tips and Tricks.


You may also like:

To create CSV, we need to loop through GridView including header and rows. While iterating, store the value in a array and in the end join the array with "," sign to form CSV.
$(document).ready(function() {
   $("#<%=txtCSV.ClientID%>").hide();
   $('#<%=btnSubmit.ClientID%>').click(function(e)
   {
     var arrCSV = [];
     var strTemp = '';
     $("#<%=gdRows.ClientID%>").find("tr").each(function () 
     {
       if ($(this).find("th").length) 
       {
         var arrHeader = [];
         $(this).find("th").each(function () {
           strTemp = $(this).text().replace(/"/g, '""');
           arrHeader.push('"' + strTemp + '"');
         });
       arrCSV.push(arrHeader.join(','));
      }
      else 
      {
        var arrData = [];
        $(this).find("td").each(function () {
         strTemp = $(this).text().replace(/"/g, '""');
         arrData.push('"' + strTemp + '"');
       });
       arrCSV.push(arrData.join(','));
      }
   });

    var strCSV = arrCSV.join('\n');
    $("#<%=txtCSV.ClientID%>").val(strCSV);
    $("#<%=txtCSV.ClientID%>").show();
    e.preventDefault();
   });
});
If you don't want to include headers in your CSV, then you can remove below code block from above code.
if ($(this).find("th").length) 
{
   var arrHeader = [];
   $(this).find("th").each(function () {
     strTemp = $(this).text().replace(/"/g, '""');
     arrHeader.push('"' + strTemp + '"');
   });
   arrCSV.push(arrHeader.join(','));
}
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Tuesday, November 19, 2013

jQuery, ASP.NET Client ID and External JS File

To find any ASP.NET Control in jQuery, we use Client ID property to get the correct ID of the rendered control. For example, to find an ASP.NET textbox with ID "txtName", a familiar jQuery syntax is,
$('<%= txtName.ClientID %>').focus( //Blah  Blah);
If you are writing this above code directly in your .aspx page, then your jQuery code will work but if you move the same code to an external or separate js (Java Script) file, you will get an error "Uncaught Error: Syntax error, unrecognized expression".

Related Post:

Any idea why this works on .aspx page?

Well the reason is, when the jQuery code is placed in .aspx page the jQuery code line such as <%=txtName.ClientID%>, is processed on the server and it is replaced with a proper ID generated by ASP.NET for the control. And when it is placed into a seperate JS file, ASP.NET has no role to play. Since the js file is not processed by ASP.NET and Client ID is not replaced, jQuery will throw the error "Uncaught Error: Syntax error, unrecognized expression" for characters < and > .

So how to fix this?

To fix this error, all you need to do is to remove < and > characters from your jQuery code. Which means you need to change your selectors and there are couples of ways to do this. For example the jQuery code,
$('<%= txtName.ClientID %>').focus( //Blah  Blah);
can be replaced with,
$("input[id*='txtName']").focus( //Blah  Blah);
The above code will select input controls which have "txtName" anywhere within the element's ID attribute value. You can also select the elements via class selectors.

If you are using ASP.NET 4.0, then you can take advantage of ClientIDMode property which when set to Static will keep the same ID in rendered page. For example:
<asp:TextBox ID="txtName" runat="server" ClientIDMode="static" />
will generate something like:
<input type="text" id="txtName" />
So your ID will not change and you don't have to use ClientID property to access the control in jQuery.

Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Wednesday, October 30, 2013

Fix for ASP.NET Checkbox -jQuery click event getting fired twice issue

This is really interesting. If ASP.NET checkboxes or checkbox list is placed within any container element like div or span, and click event is attached on checkbox. And then clicking on checkbox text will call click event twice. For example, consider the following HTML/ASP.NET code.
<div id="dvList">
<asp:CheckBox ID="chk1" runat="server" Text="Check1" CssClass="Dummy" /> 
<asp:CheckBox ID="chk2" runat="server" Text="Check2" CssClass="Dummy" /> 
</div>
Now using jQuery, bind click event to all the checkboxes which are child element of div element with ID "dvList".
$(document).ready(function(){
   $('#dvList').find('.Dummy').on('click',function(){
      alert('Test');
   });
});
If checkbox is clicked, then alert will come only once. But if click is made on text associate with checkbox, then alert will be displayed twice. Surprise!!! This is happening due to event bubbling. Before moving to event bubbling it is important to understand how checkbox is rendered in browser. A single ASP.NET checkbox,
<asp:CheckBox ID="chk1" runat="server" Text="Check1" CssClass="Dummy" /> 
is rendered in browser like,
<span class="Dummy">
   <input id="chk1" type="checkbox" name="chk1" />
   <label for="chk1">Check1 </label>
</span>
In above jQuery code, though we have setup click event handler for elements with class "Dummy" only but all the child elements also get wired to click event. We have set up a click event handler for both the <label> and the <input> and <span class="Dummy"> elements. So clicking on the <label>, the click event handler that on the label will execute, and then the click event handler set up on the <input> will execute as the label raises the click event on the <input> as well. This is exactly what event bubbling is.

To stop event bubbling, jQuery provides a method "stopPropagation()". See below jQuery code.
$(document).ready(function () {
   $('#dvList').find('.Dummy').on('click', function (evt) {
     alert('Test');
     evt.stopPropagation();
     evt.preventDefault();
  });
});
With this code, you will see alert appearing only once when you click on text but you will find that checkbox status is not getting updated. Which is due to
So, now what is the solution. Well, the solution is to first identify the element which was clicked. Whether its <label> or <span>. If its <label> or <span> then the click event will be fired twice. As explained earlier, click event first gets fired for the <label> or <span> and second time for <input>. So for the first trigger, we should simply ignore the click event by checking event target. And for next trigger, the source will be <input> so alert is fired.
$(document).ready(function(){
   $('#dvList').find('.Dummy').on('click',function(evt){
      var target = evt.target.tagName.toUpperCase();
      if (target === "LABEL" || target === "SPAN") { 
         return;
      }
      alert('Test');
   });
});
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Tuesday, August 13, 2013

Using jQuery with ASP.NET

As this post is about "using jQuery with ASP.NET" so we will not be looking into "What is jQuery" and "How to use jQuery" assuming you know basics of jQuery. If not, then please read "Learn how to use jQuery?"

To begin with using jQuery with ASP.NET, first download the latest version the jQuery library from jQuery website and unzip or copy the file in your project or Visual studio solution. Microsoft Visual studio 2010 and 2012 include jQuery by default and provide intellisense to use jQuery. Assuming that you have placed the library in Script folder, add this in the head of your ASP.NET page (simple or master). (Its a good practice to keep your all js file under Script folder).
<script src="Scripts/jquery-1.9.1.min.js" type="text/javascript"></script>
Or you can directly refer them using various CDNs. Put this line of code in head section of ASP.NET Page.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
In the above code, I have not used "http" protocol while referencing jQuery from Google CDN. Its not a mistake rather always use protocol less URL for referencing jQuery.

After this setup, you can use jQuery in your ASP.NET page. Let's see a demo.

Show alert window on click of ASP.NET Button.

Assuming a ASP.NET button with ID "btnSubmit " is placed on the page.
<asp:Button ID="btnSubmit" runat="server" Text="Button" />
And now bind the click event to ASP.NET Button in document.ready section.
<script type="text/javascript">
  $(document).ready(function() {
    $("#btnSubmit").click(function() {
         alert("Alert using jQuery");
    });
  });
</script>
In above jQuery code block, we have attached click event to the button using ID selectors. Read more about other jQuery selectors and how to use them.

Below is a list of useful jQuery code example for ASP.NET controls that we use on daily basis. One thing, while creating object of any ASP.NET control, always use ClientID. As when Master pages are used then the ID of the ASP.NET controls is changed at run time. Read more here. But with ASP.NET 4.0, this is changed and now you have control over the Client ID using ClientIDMode property.

Get label value:
$('#<%=Label1.ClientID%>').text();
Set label value:
$('#<%=Label1.ClientID%>').text("New Value");
Get Textbox value:
$('#<%=TextBox1.ClientID%>').val();
Set Textbox value:
$('#<%=TextBox1.ClientID%>').val("New Value");
Get Dropdown value:
$('#<%=DropDownList1.ClientID%>').val();
Set Dropdown value:
$('#<%=DropDownList1.ClientID%>').val("New Value");
Get text of selected item in dropdown:
$('#<%=DropDownList1.ClientID%> option:selected').text();
Get Checkbox Status:
$('#<%=CheckBox1.ClientID%>').attr('checked');
Check the Checkbox:
$('#<%=CheckBox1.ClientID%>').attr('checked',true);
Uncheck the Checkbox:
$('#<%=CheckBox1.ClientID%>').attr('checked',false);
Get Radiobutton Status:
$('#<%=RadioButton1.ClientID%>').attr('checked');
Check the RadioButton:
$('#<%=RadioButton1.ClientID%>').attr('checked',true);
Uncheck the RadioButton:
$('#<%=RadioButton1.ClientID%>').attr('checked',false);
Disable any control:
$('#<%=TextBox1.ClientID%>').attr('disabled', true);
Enable any control:
$('#<%=TextBox1.ClientID%>').attr('disabled', false);
Make textbox read only:
$('#<%=TextBox1.ClientID%>').attr('readonly', 'readonly');
I had already posted many ASP.NET related post and below you find links some useful posts.

Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Monday, February 25, 2013

Expand textarea as you type using jQuery

Textarea or ASP.NET Textbox with Multiline mode controls are useful for accepting for length inputs. If fixed height is assigned then you will find vertical scrollbar. But it will be a nice feature to expand the textarea as users types. So in this post, Find jQuery code to expand textarea as user type using jQuery plugin named "ExpandingTextarea".

Related Post:

Plugin Highlights


  • Expanding Text Areas Made Elegant
  • Mobile Friendly
  • Wide browser support. Works in IE6+, Safari, Chrome, Firefox, Opera
  • No cols hacks, or counting characters
  • Easy to style
  • Resize Friendly. Content automatically resizes without using the window.resize event or JavaScript to calculate sizes!

How to use it?


The very first thing you need to do is to download the plugin file. So once you have downloaded the file, include its reference along with jQuery reference.
<script src='expanding.js' type='text/javascript'></script>
Now, all you need to do is to define a textarea with css class 'expanding' and that's it. The plugin finds textareas with the 'expanding' class on page load and initializes them for you.
<textarea class='expanding'></textarea>
OR, if you want to use jQuery way then call "expandingTextarea()" method on the textarea element.
$(document).ready(function () {
    $("#txtNotes").expandingTextarea();
});
Live Demo
If you want to change the height and width then it can be done using simple css.
textarea{
    min-height: 6em;
    max-height: 8em;
    width:400px;
}
Official Website
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Monday, February 11, 2013

Highlight Negative value columns in ASP.NET GridView using jQuery

In this post, find jQuery code to highlight negative value columns/cells in ASP.NET GridView. This is a helpful feature as it draws user's attention immediately and informs him that there is something wrong with some of the entities.


Related Post:

How to do it?


Define a style sheet class which will be used to highlight negative column value.
.negative
{
   font-weight: bold;
   color:red;
}
  • Iterate through all tr elements and select column which may have negative values. For demo, Quantity column is selected.
  • Cache the required column and check it's text. If text is numeric and less than 0 then apply style sheet to it.
So putting it together the complete jQuery code is,
$(document).ready(function () {
  $("#<%=gdRows.ClientID%> tr:has(td)").each(function () {
    var $tdElement = $(this).find("td:eq(2)"); //Cache Quantity column.
    var cellText = $tdElement.text();
    if ($.isNumeric(cellText)) 
    {
       var iNum = parseInt(cellText);
       if (iNum < 0) 
          $tdElement.addClass('negative');
    }
  });
});


Now, the above jQuery code is specific to a column and what if there are multiple columns which may contain negative values and you want to highlight them as well then above code will not work. The generic solution will be to iterate through all columns and see if they are negative. If yes, then highlight them.
$(document).ready(function () {
  $("#<%=gdRows.ClientID%> td").each(function () {
      var cellText = $(this).text();
      if ($.isNumeric(cellText)) 
      {
         var iNum = parseInt(cellText);
         if (iNum < 0) 
            $tdElement.addClass('negative');
      }
  });
});

Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Monday, January 7, 2013

Turn off autocomplete for textbox in ASP.Net using jQuery

jQuery code to turn off autocomplete for ASP.NET textbox.
$(document).ready(function(){
  $("#<%=Textbox.ClientID %>").attr("autocomplete", "off");
});
But there is no need to use jQuery for this as this can be done easily just by setting attribute for ASP.NET textbox.
<asp:TextBox runat="server" ID="Textbox" autocomplete="off"/>
But jQuery can be useful, if there are many ASP.NET textboxes then jQuery can be useful. Instead of setting attribute for every textbox can take time but using jQuery you can turn off using jQuery.

Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Thursday, January 3, 2013

Check/uncheck checkboxes in Asp.net GridView using jQuery

Find out jQuery code to check/uncheck or select/deselect all the checkboxes in ASP.NET Gridview. There are already plenty of articles on this topic but then how this is different. Assume, all the checkboxes are checked when header checkbox is checked but then you uncheck one of the child checkbox then what happens to your header checkbox? It should also get unchecked. Right? That's is where this post is different from others.

In this post, find jQuery code to
- Check/uncheck all child checkbox based on parent checkbox status.
- Update parent checkbox status based on child checkbox status.


Also Read:

How to do it?


  • Bind the click event to parent checkbox of ASP.NET GridView.
$('#gdRows').find('input:checkbox[id$="chkParent"]').click( function() {
});
  • In the click event, based on the parent checkbox status set the child checkbox status.
var isChecked = $(this).prop("checked");
$("#gdRows [id*=chkSelect]:checkbox").prop('checked',isChecked);
  • So the complete code for parent checkbox click event is,
$('#gdRows').find('input:checkbox[id$="chkParent"]').click( function() 
{
    var isChecked = $(this).prop("checked");
    $("#gdRows [id*=chkSelect]:checkbox").prop('checked',isChecked);
});
  • Now, based on the child checkbox status also need to update the parent checkbox. For example, if out of all the child checkboxes, one is unchecked then parent checkbox should also be checked.

    So for this, attach an click event handler to all the child checkboxes of ASP.NET GridView.
$('#gdRows').find('input:checkbox[id$="chkSelect"]').click(function() {
});
  • In this event, first define a flag with true value. And then loop through all the child checkbox and if one of the child checkbox is unchecked then set the flag value to false. And then update parent checkbox status value based on the flag variable value.
var flag = true;
$("#gdRows [id*=chkSelect]:checkbox").each(function() {
      if ($(this).prop("checked") == false) 
        flag = false;
});
$("#gdRows [id*=chkParent]:checkbox").prop('checked', flag);
So putting it together the complete jQuery code is,
$(document).ready(function() {
  
  $('#gdRows').find('input:checkbox[id$="chkParent"]').click(function() 
  {
     var isChecked = $(this).prop("checked");
     $("#gdRows [id*=chkSelect]:checkbox").prop('checked', isChecked);
  });
  
  
  $('#gdRows').find('input:checkbox[id$="chkSelect"]').click(function() 
  {
     var flag = true;
     $("#gdRows [id*=chkSelect]:checkbox").each(function() {
         if ($(this).prop("checked") == false) 
           flag = false;
     });
     $("#gdRows [id*=chkParent]:checkbox").prop('checked', flag);
  });

});​
See result below


Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Friday, December 21, 2012

jQuery to highlight GridView Rows when Checkbox is checked in ASP.NET

In this post, Find out jQuery code to highlight ASP.NET Gridview row when checkbox is checked and restore it to original state when unchecked.


Also Read:

How to do it?


  • Bind the click event to all the checkbox of ASP.NET GridView.
    $('#<%=gdRows.ClientID%>')
         .find('input:checkbox[id$="chkDelete"]')
         .click( function() {
    });
    
  • In the click event, first check whether the checkbox is checked or unchecked. And store the status in a variable.
    var isChecked = $(this).prop("checked");
  • After that find the respective row where checkbox is present. As we need to highlight that particular row only.
    var $selectedRow = $(this).parent("td").parent("tr");
  • If you have different color for alternate rows (see above image) then next few lines of code is required, otherwise you can skip it. For example, if all the rows of same color then skip this code. But if there are alternate color of GridView rows then it is required.

    As once we highlight the row, we can't find what was the previous color once it is unchecked. So the idea is to find the row index. Based on index value (even or odd) set color value in variable.
    var selectedIndex = $selectedRow[0].rowIndex;
    var sColor = '';
    if(selectedIndex%2 == 0)
        sColor = 'PaleGoldenrod';
    else
        sColor = 'LightGoldenrodYellow';
    
  • Now based on checkbox status, highlight the row (if checked). Otherwise restore it to previous color which is stored in sColor variable.
    if(isChecked)
        $selectedRow.css({
            "background-color" : "DarkSlateBlue",
            "color" : "GhostWhite"
        });
    else
       $selectedRow.css({
            "background-color" : sColor,
            "color" : "black"
        });
    
So putting it together the complete jQuery code is,
$(document).ready(function() 
{
  $('#<%=gdRows.ClientID%>')
     .find('input:checkbox[id$="chkDelete"]').click(function()
     {
        var isChecked = $(this).prop("checked");
        var $selectedRow = $(this).parent("td").parent("tr");
        var selectedIndex = $selectedRow[0].rowIndex;
        var sColor = '';
            
        if(selectedIndex%2 == 0)
            sColor = 'PaleGoldenrod';
        else
            sColor = 'LightGoldenrodYellow';
                
        if(isChecked)
            $selectedRow.css({
                "background-color" : "DarkSlateBlue",
                "color" : "GhostWhite"
            });
        else
           $selectedRow.css({
               "background-color" : sColor,
               "color" : "black"
          });
    });     
});
See result below


Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Friday, November 9, 2012

jQuery code to hide table rows with empty td element

Find jQuery code to hide those table rows (<tr>) which have at least one or more <td> element as empty or with no value. To hide table rows, iterate through all the td element and check it's text. If it is empty then hide it's parent (which is tr) using .hide().

Related Post:
$(document).ready(function() {
    $("#gdRows tr td").each(function() {
        var cellText = $.trim($(this).text());
        if (cellText.length == 0) {
            $(this).parent().hide();
        }
    });
});​
See result below


See Complete Code
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

jQuery code to highlight empty table element

Find jQuery code to highlight those <td> elements within a table/ Grid/ GridView/ DataGrid which have no value associated with it or which are empty.

All is required is to loop through all the <td> element and check it's value. If it is empty, then assign background color to it so that it looks highlighted.
$(document).ready(function() {
    $("#gdRows td").each(function() {
        var cellText = $(this).text();
        if ($.trim(cellText) == '') 
        {
            $(this).css('background-color', 'LightGreen');
        }
    });
});​
See result below


If you want then you can also assign some default data to these empty <td> elements. Using text() method set the default text.
$(document).ready(function() {
    $("#gdRows td").each(function() {
        var cellText = $(this).text();
        if ($.trim(cellText) == '') 
        {
            $(this).text('N/A');
        }
    });
});​
See Complete Code
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Monday, July 9, 2012

Validate ASP.NET DropDownList using jQuery

In this small post, today I will show you how to validate ASP.NET DropDown List using jQuery.

Let's declare a DropDownList.
<asp:DropDownList ID="ddlList" runat="server">
   <asp:ListItem Text="Select" Value="0" />
   <asp:ListItem Text="jQuery" Value="1"></asp:ListItem>
   <asp:ListItem Text="JavaScript" Value="2"></asp:ListItem>
   <asp:ListItem Text="Prototype" Value="3"></asp:ListItem>
   <asp:ListItem Text="Dojo" Value="4"></asp:ListItem>
   <asp:ListItem Text="Mootools" Value="5"></asp:ListItem>
</asp:DropDownList>
To validate the dropdown list, all you need to do is to get the selected value and check if it is not 0. If 0, then nothing is selected so alert the user, otherwise proceed.
$(document).ready(function() {
    $('#btnValidateByVal').on('click', function(e) {
        var iVal = $('#ddlList').val();
        if (iVal == 0) 
        {
            alert('Please select any technology.');
            e.preventDefault();
        }
        else 
            alert('Well Done!!!!');
   })
})​
In the above jQuery code, the validation is done using value of the selected item. But you can also validate the dropdown using the selected item text.
$(document).ready(function() {
    $('#btnValidateByText').on('click', function(e) {
        var sText = $('#ddlList1 option:selected').text().toLowerCase();
        if (sText == 'select') 
        {
            alert('Please select any technology.');
            e.preventDefault();
        }
        else 
           alert('Well Done!!!!');
    })
})​
Note: Above both jQuery codes will work only with jQuery 1.7 or higher version as I have used .on() method to bind the click event and .on was introduced in jQuery 1.7. So if you are using below version then you can either .live() or .bind() method.

Suggested Post,
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Wednesday, July 4, 2012

Validate ASP.NET RadioButtonList using jQuery

ASP.NET RadioButtonList control is used to create a group of radio buttons, where all are rendered as an individual <input type=radio></input>. So in this post, I will show you how to validate ASP.NET RadioButtonList using jQuery.

Let's declare a RadioButtonList.
<asp:RadioButtonList ID="rdlList" runat="server">
    <asp:ListItem Text="jQuery" Value="jQuery"></asp:ListItem>
    <asp:ListItem Text="JavaScript" Value="JavaScript"></asp:ListItem>
    <asp:ListItem Text="Prototype" Value="Prototype"></asp:ListItem>
    <asp:ListItem Text="Dojo" Value="Dojo"></asp:ListItem>
    <asp:ListItem Text="Mootools" Value="Mootools"></asp:ListItem>
</asp:RadioButtonList>
As you can see there are 5 radio buttons and the validation would be to select at least one option. For demo, I will validate the radiobuttonlist on click of button. We can use length property to find out, if any radio button is selected or not.

$("#rdlList :radio:checked").length; will return 1 if anything is selected, otherwise 0.
$(document).ready(function() {
    $('#btnSubmit').on('click', function(e) {
        var cnt = $("#rdlList :radio:checked").length;
        if (cnt == 0) 
        {
            alert('Select any option.');
            e.preventDefault();
        }
        else 
            alert('Well Done!!!!');
    });
});​
Note: This code will work only with jQuery 1.7 or higher version as I have used .on() method to bind the click event and .on was introduced in jQuery 1.7. So if you are using below version then you can either .live() or .bind() method.

Suggested Post,
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Monday, July 2, 2012

Validate ASP.NET CheckboxList using jQuery

ASP.NET CheckBoxList is group of checkboxes which is used to create a multi-selection check box group. In this post, I will show you how to validate ASP.NET CheckBoxList using jQuery.

Let's declare a CheckboxList.
<asp:CheckBoxList ID="CheckBoxList1" runat="server">
    <asp:ListItem Text="Singing" Value="Singing"></asp:ListItem>
    <asp:ListItem Text="Writing" Value="Writing"></asp:ListItem>
    <asp:ListItem Text="Travelling" Value="Travelling"></asp:ListItem>
    <asp:ListItem Text="Blogging" Value="Blogging"></asp:ListItem>
    <asp:ListItem Text="Sports" Value="Sports"></asp:ListItem>
</asp:CheckBoxList>
As you can see there are 5 checkboxes and the validation would be to select at least 3 technologies. And on click of button, validate the checkboxlist. To find out, how many checkboxes are checked, use length property to find out.

$("#CheckBoxList1 input:checked").length; will give count of checked checkboxes out of the list.
$(document).ready(function() {
    $('#btnSubmit').on('click', function(e) {
        var cnt = $("#CheckBoxList1 input:checked").length;
        if (cnt < 3) 
        {
            alert('Select at least 3 technologies');
            e.preventDefault();
        }
        else 
            alert('Well Done!!!!');
    });
});​
Note: This code will work only with jQuery 1.7 or higher version as I have used .on() method to bind the click event and .on was introduced in jQuery 1.7. So if you are using below version then you can either .live() or .bind() method.

Suggested Post,
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Thursday, June 7, 2012

Show loading image while Page is loading using jQuery

Web pages takes time to load and sometimes when page is heavy (full of images) then it takes more time to load. Would it not be nice to show loading images or message while your page is loading. It creates responsive webpage and gives nice user experience. The user will come to know that something is loading.

Earlier I had posted about Execute jQuery code only after Web Page is loaded completely and Show loading icon while actual image is loading using jQuery. In this post, I will show you how to show loading icon/image while page is loading using jQuery.

How to do it?

First create a div element and assign an ID to it. I have assigned ID as "dvLoading". This div element will be used to show the loading icon.
<div id="dvLoading"></div>
Now create a style which will be applied to the div element. Basically, this CSS style will set the div position in the middle of the page and also assign width and height. And the background of the div will be an loading gif image.
#dvLoading
{
   background:#000 url(images/loader.gif) no-repeat center center;
   height: 100px;
   width: 100px;
   position: fixed;
   z-index: 1000;
   left: 50%;
   top: 50%;
   margin: -25px 0 0 -25px;
}
Now, comes the jQuery part. The div element will be always visible but we need to hide it as soon as our page is loaded completely. In this case, we can't use $(document).ready() to show the loading div. Read here why? Therefore, we need to use window.load event to hide the loading div element. Remember to put this code before closing head tag.
<script>
$(window).load(function(){
  $('#dvLoading').fadeOut(2000);
});
</script>
That's it!!!!!
Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Tuesday, May 29, 2012

Things to remember while using jQuery with ASP.NET Master Pages

jQuery is great library but if not used properly then it can make you crazy. If you are using ASP.NET Master Page and planning to use jQuery as well then it is quite important to know few things otherwise your code is not going to work. I have prepared a checklist which you should remember or take care while using jQuery with ASP.NET Master Pages.


  • Ensure that if you have already include jQuery library in master page, then please don't include in Content Page.

  • The ASP.NET Master Page and Content Page gets merged into a single page when render in the browser. And browsers always executes the page from top to bottom. So remember, that jQuery code placed in Master Page will always gets executed first.

  • If you are using .NET 3.5 or below version then when Master pages are used then ID of the control placed in Content Page gets changed at run time. The Master Page ID is pre-pended to all controls on the content page. This is true only for control which have runat="server" attribute associated with them. So always use ClientID property to access control in jQuery.

    Below jQuery code access label element directly with its ID but this will fail.
    $('Label1').text();
    
    The correct way is,
    $('#<%=Label1.ClientID%>').text();
    
    So always use ClientID Property while accessing control in jQuery, if you are using Master Page. Also read "Useful jQuery code examples for ASP.NET Controls"

  • If you have include $(document).ready() in Master Page that doesn't mean that you can't include on Content Page. You can have many $(document).ready() blocks on your page. But remember it gets executed from top to bottom.

  • If you are using jQuery and Ajax with Master Page then please read "Use jQuery and Ajax together with ASP.NET Master pages"

Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...

Wednesday, May 23, 2012

GridView and jQuery in ASP.NET

Read more...

Tuesday, May 22, 2012

Download White Paper for Building 100% Native Mobile Apps with ASP.NET MVC

Gartner predicts that smartphones and tablets will represent more than 90% of the net new growth in device adoption for the coming four years. The mobile device market is extremely fragmented, requiring the targeting of at least four vastly different platforms for most business applications. The market fragmentation causes complications for software developers.


This white paper describes how to meet this challenge by leveraging the power of ASP.NET MVC to build standards compliant, 100% native applications for mobile devices. This white paper will detail how to:

  • Leverage the power of the ASP.NET MVC platform.
  • Harness existing knowledge of HTML, CSS, C#, and JavaScript to build cutting edge, 100% native applications for all leading mobile platforms including iOS, Android, and Windows Phone 7.1.
  • Maintain a single source base and deploy native solutions on all leading mobile platforms.

Feel free to contact me for any help related to jQuery, I will gladly help you.
Read more...