Sunteți pe pagina 1din 43

Useful jQuery code examples for

ASP.NET Controls
In this post, you will see list of some 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. Get label value:
1 $('#<%=Label1.ClientID%>').text();
Set label value:
1 $('#<%=Label1.ClientID%>').text("New Value");
Get Textbox value:
1 $('#<%=TextBox1.ClientID%>').val();
Set Textbox value:
1 $('#<%=TextBox1.ClientID%>').val("New Value");
Get Dropdown value:
1 $('#<%=DropDownList1.ClientID%>').val();
Set Dropdown value:
1 $('#<%=DropDownList1.ClientID%>').val("New Value");
Get text of selected item in dropdown:
1 $('#<%=DropDownList1.ClientID%> option:selected').text();
Get Checkbox Status:
1 $('#<%=CheckBox1.ClientID%>').attr('checked');
Check the Checkbox:
1 $('#<%=CheckBox1.ClientID%>').attr('checked',true);
Uncheck the Checkbox:
1 $('#<%=CheckBox1.ClientID%>').attr('checked',false);
Get Radiobutton Status:
1 $('#<%=RadioButton1.ClientID%>').attr('checked');
Check the RadioButton:
1 $('#<%=RadioButton1.ClientID%>').attr('checked',true);
Uncheck the RadioButton:
1 $('#<%=RadioButton1.ClientID%>').attr('checked',false);
Disable any control:
1 $('#<%=TextBox1.ClientID%>').attr('disabled', true);
Enable any control:
1 $('#<%=TextBox1.ClientID%>').attr('disabled', false);
Make textbox read only:
1 $('#<%=TextBox1.ClientID%>').attr('readonly', 'readonly');
Share your useful code as well (via commenting), I will add this into this list.

Mostly used and essential jQuery code


examples
The advantage of having ready made code examples is that they will save your valuable time.I have prepared a
list of common and mostly used jQuery code snippets/example which can be used in any project. These
examples are small but yet powerful and essential. I suggest you to bookmark this page and support us by
clicking the Google +1 button (Just below the article title).
 Hide all elements of HTML form using jQuery
 Disable/Enable an element using jQuery
 How to get HTML of any control using jQuery
 How to set HTML of any control using jQuery
 How to Check element exists or not in jQuery
 How to Disable right click using jQuery
 How to get mouse cursor position
 Find which mouse button clicked using jQuery
 Disable-Enable all controls of page using jQuery
 Enable/Disable all text boxes using jQuery
 Make readonly textbox using Jquery
 Split function in jQuery
 Using trim() function in jQuery
 Detect Browsers using jQuery
 Get ASP.NET Dropdown selected value and text using jQuery
 Set Max Length for ASP.NET MultiLine Textbox using jQuery
 jQuery Code: Change text to Uppercase
 How to scroll to the bottom of a textarea using jQuery
 Disable Cut, Copy and Paste function for textbox using jQuery
 Validate Date of Birth is not greater than current date using jQuery
 How to Zoom an image using jQuery
 How to Zoom image on mouseover using jQuery
 How to zoom element text on Mouseover using jQuery
 jQuery code to allow only numbers in textbox
 jQuery code to allow numbers and arrow keys in textbox
 jQuery code to allow numbers, alphabets or specific characters
 Determine which key was pressed using jQuery
 How to Disable Spacebar in text box using jQuery
 Useful jQuery code examples for ASP.NET Controls
 jQuery to Retrieve Server's current date and time with ASP.NET
 Validate email address using jQuery
 How to Set focus on First textbox of page using jQuery
 Get total count of textboxes using jQuery
 How to set focus on next textbox on Enter Key using jQuery
 How to Replace All Text On Page using jQuery
 How to put link on image using jQuery
 Check/Uncheck All Checkboxes with JQuery
 Highlight row on mouseover in GridView using jQuery
 Formatting ASP.NET GridView using jQuery
Hide all elements of HTML form using
jQuery
If you want to hide all the elements of the form then below jQuery code will help you to achieve this.
1 <script type="text/javascript">
2 $(document).ready(function(){
3 $("#form1").hide()
4 });
5 </script>

"form1" is the Id of the HTML form. Hide() function can be used with any control. If you don't want to hide all the
elements of the form but you want to hide elements of particular div, then you can use hide() function on div
element also. Suppose a div is declare with id "dvElement" then
1 <script type="text/javascript">
2 $(document).ready(function(){
3 $("#dvElement").hide()
4 });
5 </script>

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

Disable/Enable an element using


jQuery
Labels: jQuery, jQuery Code Examples, Jquery Code Snippets, jQuery Codes
You must have come across a situation where you have to make any element disable or enable.There are couple
of ways using them you can enable/disable any element using jquery. jQuery really makes your task very easy. In
below given example, I have disabled a textbox with id "txtName".

Approach 1
1 $("#txtName").attr("disabled", true);
Approach 2
1 $("#txtName").attr("disabled", "disabled");
If you wish to enable any element then you just have to do opposite of what you did to make it disable. However
jQuery provides another way to remove any attribute.

Approach 1
1 $("#txtName").attr("disabled", false);
Approach 2
1 $("#txtName").attr("disabled", "");
Approach 3
1 $("#txtName").removeAttr("disabled");
That's is. This is how you enable or disable any element using jQuery.

Feel free to contact me for any help related to jQuery. I will gladly help you.
How to get HTML of any control using
jQuery
Labels: jQuery, jQuery Code Examples, Jquery Code Snippets, jQuery Codes, jQuery Functions, jQuery
Methods, Methods
In this post, we will see that how we can get the HTML part or I should say innerHTML of any control. Well,
jQuery provides a function "html()" which will give the html of the control. For example, I have placed a div control
on the page which has h1 and h2 tag.

1 <div id="dvExample">
2 <h1>
3 jQuery By Example Rocks..
4 </h1>
5 <h2>
6 It has really cool tips.
7 </h2>
8 </div>

Below jQuery code will display an alert with div's html.

1 $(document).ready(function()
2{
3 alert($("#dvExample").html());
4 });

Output:

How to set HTML of any control using


jQuery
Labels: jQuery, jQuery Code Examples, Jquery Code Snippets, jQuery Codes, jQuery Functions, jQuery
Methods, Methods

In my previous post "How to get HTML of any control using jQuery", I had explained that how can we get the
HTML of any control. In this post, I will show you how can you set HTML for any control. Well, we will use the
same function html() using which we get the HTML. This function "html()" also takes an argument. Value passed
in the argument will be the new content of the div. For example, I have placed a div control on the page which
has h1 and h2 tag.
1 <div id="dvExample">
2 <h1>
3 jQuery By Example Rocks..
4 </h1>
5 <h2>
6 It has really cool tips.
7 </h2>
8 </div>
Below jQuery code will set the div content and display the new content. I will remove h1 and h2 tag and will place
h3 tag.
1 $(document).ready(function()
2{
3 $("#dvExample").html('<h3>I am new content of the div.</h3>')
4 alert($("#dvExample").html());
5 });

Output:

How to Check element exists or not in


jQuery
Labels: jQuery, jQuery Code Examples, Jquery Code Snippets, jQuery Codes, jQuery Interview Question
Have you ever thought that what will happen if you try to access an element using jQuery which does not exist in
your DOM? For example, I am accessing "dvText" element in below code and that element does not exists in my
DOM.
1 var obj = $("#dvText");
2 alert(obj.text());
What will happen?

There could be 2 possibilities. Either an error will be thrown and rest of the code will not get executed OR Nothing
will happen.

If you think that error will be thrown then you are wrong. In jQuery, you don't need to be worried about checking
the existence of any element. If element does not exists, jQuery will do nothing.
See live Demo and Code
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Check element exists</title>
<script type="text/javascript"
src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js">
</script>

<script type="text/javascript">
$(document).ready(function(){
if($("#dvText").length){
alert(obj.text())
}
});
</script></head>
<body>
<form id="form1" runat="server">
<div id="dvParent">
<div id="dvChild">
<p><span id="spnText">jQuery By Example Rocks!!!</span> </p>
</div>
</div>
</form>
</body>
</html>
Then what is this post all about? As post title says "How to Check element exists or not in jQuery", where you are
not worried about element existence as jQuery handles it quite well. Well, Let say there is some long code related
to the element you want to execute and you are not sure that element exists or not. jQuery doesn't throw error
but that doesn't mean that you don't check the existence. So it's always better to check the existence. So how do
we check it? See below code
1 if ($('#dvText').length) {
2 // your code
3}
jQuery provides length property for every element which returns 0 if element doesn't exists else length of the
element.
See live Demo and Code
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Check element exists</title>
<script type="text/javascript"
src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js">
</script>

<script type="text/javascript">
$(document).ready(function(){
var obj = $("#dvText");
alert(obj.text());
});
</script></head>
<body>
<form id="form1" runat="server">
<div id="dvParent">
<div id="dvChild">
<p><span id="spnText">jQuery By Example Rocks!!!</span> </p>
</div>
</div>
</form>
</body>
</html>
Feel free to contact me for any help related to jQuery, I will gladly help you.

How to Disable right click using jQuery


Labels: jQuery, jQuery Code Examples, Jquery Code Snippets, jQuery Codes, jQuery Tips
You can find many java script code snippets to disable right click. But jQuery makes our life easy. Below jQuery
code disables the right click of mouse.
1 $(document).ready(function(){
2 $(document).bind("contextmenu",function(e){
3 return false;
4 });
5 });
See live Demo and Code
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Disable Right Click Demo</title>
<script type="text/javascript"
src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js">
</script>

<script type="text/javascript">
$(document).ready(function(){
$(document).bind("contextmenu",function(e){
return false;
});
});
</script>
</head>
<body>
<p id="hello">Hello World. Right click of mouse is disabled.</p>
</body>
</html>
We just need to bind the contextmenu event with the document element.

Method 2 (Send from one of the reader):


1 $(document).ready(function(){
2 $(document).bind("contextmenu",function(e){
3 e.preventDefault();
4 });
5 });
Feel free to contact me for any help related to jQuery. I will gladly help you.

Jquery Tip: How to get mouse cursor


position
Labels: jQuery, jQuery Code Examples, Jquery Code Snippets, jQuery Codes, jQuery Tips
In this jQuery tip post, We will see how can we get the mouse cursor position using jQuery. See below jQuery
code.
1 $(document).ready(function(){
2 $(document).mousemove(function(e){
3 $('#spnCursor').html("X Axis : " + e.pageX + " Y Axis : " + e.pageY);
4 });
5 });
When the DOM is ready, we listen for mousemove event. Whenever user moves the mouse then this event gets
called and we bind the pageX and pageY property to the span element.
See live Demo and Code.
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>How to get mouse cursor position Demo</title>
<script type="text/javascript"
src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$(document).mousemove(function(e){
$('#spnCursor').html("X Axis : " + e.pageX + "<br/> Y Axis : " + e.pageY);
});
});
</script>
</head>
<body>
<span id="spnCursor"></span>
</body>
</html>
Don't forget to read:
Mostly asked jQuery interview questions list.

Mostly asked jQuery interview


questions list
Labels: jQuery, jQuery Interview Question
jQuery is rocking and it has become so popular that it is used almost by every developer. As it has already
become more popular, interviewers tend to ask jQuery questions in interview. Below is the list of questions which
are asked in almost every jQuery interview. Before you go further, please read my previous article published
already about jQuery interview question.
 jQuery Interview Question
Okay, so I assume that you have read the above article. Let's see some more jQuery interview questions.
 Is jQuery a library for client scripting or server scripting?
Ans: Client scripting
 Is jQuery a W3C standard?
Ans: No
 What are jQuery Selectors?
Ans: Selectors are used in jQuery to find out DOM elements. Selectors can find the elements via ID, CSS,
Element name and hierarchical position of the element.
 The jQuery html() method works for both HTML and XML documents?
Ans: It only works for HTML.
 Which sign does jQuery use as a shortcut for jQuery?
Ans: $(dollar) sign.
 What does $("div") will select?
Ans: It will select all the div element in the page.
 What does $("div.parent") will select?
Ans: All the div element with parent class.
 What is the name of jQuery method used for an asynchronous HTTP request?
Ans: jQuery.ajax()

Mostly used and essential jQuery code snippets.

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

Find which mouse button clicked using


jQuery
Labels: jQuery, jQuery Code Examples, Jquery Code Snippets, jQuery Codes, jQuery Tips
For one of my requirement, I need to determine which mouse button (Left, Middle or Right) was clicked. jQuery
provides mousedown() event, using which we can check which mouse button is clicked. For key or button events,
event attribute indicates the specific button or key that was pressed. event.which will give 1, 2 or 3 for left, middle
and right mouse buttons respectively. The advantage of using event.which is that it eliminates cross browser
compatibility.
view sourceprint?
01 $(document).ready(function() {
02 $('#btnClick').mousedown(function(event){
03 switch (event.which) {
04 case 1:
05 alert('Left mouse button pressed');
06 break;
07 case 2:
08 alert('Middle mouse button pressed');
09 break;
10 case 3:
11 alert('Right mouse button pressed');
12 break;
13 default:
14 break;
15 }
16 });
17 });

Disable-Enable all controls of page


using jQuery
Labels: jQuery, jQuery Code Examples, Jquery Code Snippets, jQuery Codes, jQuery Selectors, jQuery Tips
In this post, I will demonstrate a simple jQuery code to disable and enable all the controls of the page. jQuery
provides (*) selector, which selects all the element of the page. We will use the * selector to disable and enable
all the elements. For demo purpose, we will disable and enable controls on click of button. See below jQuery
code.
01 $(document).ready(function() {
02 $(document).ready(function(){
03 $("#btnEnableDisable").toggle(function() {
04 $("*").attr("disabled", "disabled");
05 $(this).attr("disabled", "");
06 }, function() {
07 $("*").attr("disabled", "");
08 });
09 });
10 });

As it's clear from code, toggle function is used for button. We set the "disabled" attribute of all the controls to
"disabled" to make all the control disable. To enable all the control, we set blank value to "disabled" attribute.
One thing to note here is that when we are disabling all the controls, it will also disable the button control. So we
need to enable the button control, while disabling all the controls.
Jquery Tip: How to get mouse cursor
position
Labels: jQuery, jQuery Code Examples, Jquery Code Snippets, jQuery Codes, jQuery Tips
In this jQuery tip post, We will see how can we get the mouse cursor position using jQuery. See below jQuery
code.
1 $(document).ready(function(){
2 $(document).mousemove(function(e){
3 $('#spnCursor').html("X Axis : " + e.pageX + " Y Axis : " + e.pageY);
4 });
5 });
When the DOM is ready, we listen for mousemove event. Whenever user moves the mouse then this event gets
called and we bind the pageX and pageY property to the span element.
See live Demo and Code.
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title></title>
<link type="text/css"
rel="Stylesheet"href="http://ajax.microsoft.com/ajax/jquery.ui/1.8.5/themes/redmond/jquery-ui.css" />
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</script>

<script type="text/javascript">
$(document).ready(function(){
$("#btnEnableDisable").toggle(function() {
$("*").attr("disabled", "disabled");
$(this).attr("disabled", "");
}, function() {
$("*").attr("disabled", "");
});
});
</script>
</head>
<body>
First name: <input type="text" name="firstname" /><br />
Last name: <input type="text" name="lastname" /><br />
Password: <input type="password" name="pwd" /><br/>
<input type="radio" name="sex" value="male" /> Male<br />
<input type="radio" name="sex" value="female" /> Female <br/><br/>
<input type="checkbox" name="vehicle" value="Bike" /> I have a bike<br />
<input type="checkbox" name="vehicle" value="Car" /> I have a car <br/><br/>
<select name="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select><br/>
<textarea rows="5" cols="40" > </textarea>
<br/><br/>
<INPUT TYPE="button" id="btnEnableDisable" VALUE="Enable/Disable">
</body>
</html>
Don't forget to read:
Mostly asked jQuery interview questions list.
Mostly used and essential jQuery code snippets.
Feel free to contact me for any help related to jQuery. I will gladly help you.
Enable/Disable all text boxes using
jQuery
Labels: jQuery, jQuery Code Examples, Jquery Code Snippets, jQuery Codes, jQuery Tips
In my previous post "jQuery code to disable-enable all controls of page", we saw how can we disable all the
controls of the page. For my project, we had requirement where we need to disable only the text boxes not all the
controls. It was not tough with jQuery. Few minutes of work. See below jQuery code.
1 $("#btnEnableDisable").toggle(function() {
$("INPUT[type=text],INPUT[type=password],TEXTAREA").attr("disabled", "di
2
sabled");
3 $(this).attr("disabled", "");
4 }, function() {
$("INPUT[type=text],INPUT[type=password],TEXTAREA").attr("disabled", "")
5
;
6 });
See live Demo and Code.
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title></title>
<link type="text/css" rel="Stylesheet"href="http://ajax.microsoft.com/ajax/jquery.ui/1.8.5/themes/redmond/jquery-
ui.css" />
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</script>

<script type="text/javascript">
$(document).ready(function(){
$("#btnEnableDisable").toggle(function() {
$("INPUT[type=text],INPUT[type=password],TEXTAREA").attr("disabled", "disabled");
$(this).attr("disabled", "");
}, function() {
$("INPUT[type=text],INPUT[type=password],TEXTAREA").attr("disabled", "");
});
});
</script>
</head>
<body>
First name: <input type="text" name="firstname" /><br />
Last name: <input type="text" name="lastname" /><br />
Password: <input type="password" name="pwd" /><br/>
<input type="radio" name="sex" value="male" /> Male<br />
<input type="radio" name="sex" value="female" /> Female <br/><br/>
<input type="checkbox" name="vehicle" value="Bike" /> I have a bike<br />
<input type="checkbox" name="vehicle" value="Car" /> I have a car <br/><br/>
<select name="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select><br/>
<textarea rows="5" cols="40" > </textarea>
<br/><br/>
<INPUT TYPE="button" id="btnEnableDisable" VALUE="Enable/Disable Textbox">
</body>
</html>
Feel free to contact me for any help related to jQuery. I will gladly help you.
How to make readonly textbox using
Jquery
Labels: jQuery, jQuery Code Examples, Jquery Code Snippets, jQuery Codes, jQuery Tips
Sometimes making a textbox readonly is project need. There are 2 ways to make textbox readonly using jQuery.

Method 1:
1 <script type="text/javascript">
2 $(document).ready(function(){
3 $("#<%=txtName.ClientID %>").focus(function () {
4 $(this).blur();
5 });
6 });
7 </script>
See live Demo and Code

Method 2:
1 <script type="text/javascript">
2 $(document).ready(function(){
3 $("#<%=txtName.ClientID %>").attr('readonly', true);
4 });
5 </script>
Feel free to contact me for any help related to jQuery. I will gladly help you.

Split function in jQuery


Labels: jQuery, jQuery Functions, jQuery Methods, Methods
jQuery provides a method "split()", which splits the text. We can use any delimiter to split the text. Let me explain
you with an example. First declare a label and assign some text to it. We will split the text using space as
delimiter.
1 <asp:Label ID="lblMessage" runat="server"
2 Text="jQuery By Example Rocks!!" />
See below jQuery code, which makes use of split function and split the string with space.
1 <script type="text/javascript">
2 $(document).ready(function(){
3 var element = $("#lblMessage").text().split(" ");
4 alert(element);
5 });
6 </script>
Thing to note here is the variable "element" declared in jQuery code becomes an array and you can easily iterate
through it. If you say alert(element[0]) then it will alert jQuery.
See live Demo and Code
Don't forget to read
Mostly used and essential jQuery code snippets.
Mostly asked jQuery interview questions list.
Read my other helpful posts:
Disable/Enable an element using jQuery
Disable-Enable all controls of page using jQuery
Enable/Disable all text boxes using jQuery
Feel free to contact me for any help related to jQuery. I will gladly help you.

Using trim() function in jQuery


Labels: jQuery, jQuery Functions, jQuery Methods, Methods
jQuery also have trim function like javascript trim, which removes spaces from starting and from end of the string.
See below code.
1 <script type="text/javascript">
2 $(document).ready(function(){
3 var str = " I Love jQuery ";
4 str = jQuery.trim(str);
5 alert(str);
6 });
7 </script>

Output of this would be "I Love jQuery". trim function only removes spaces from starting and end of the string. If
there are any space between middle of the statement that is ignored.

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Split function Demo</title>
<script type="text/javascript"
src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js">
</script>

<script type="text/javascript">
$(document).ready(function(){
var element = $("#lblMessage").text().split(" ");
alert(element[0]);
alert(element[1]);
});
</script>
</head>
<body>
<span id="lblMessage">jQuery By Example Rocks!!</span>
</body>
</html>

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

Detect Browsers using jQuery


Labels: jQuery, jQuery Code Examples, Jquery Code Snippets, jQuery Codes, jQuery Tips
jQuery provides a property to detect the browser. It works well for IE, mozilla, Safari and opera browser but it
doesn't work for Google Chrome. Below jQuery code gives you an idea about $.browser property.
01 $(document).ready(function() {
02 if ($.browser.mozilla && $.browser.version >= "2.0" ){
03 alert('Mozilla above 1.9');
04 }
05
06 if( $.browser.safari ){
07 alert('Safari');
08 }
09
10 if( $.browser.opera){
11 alert('Opera');
12 }
13
14 if ($.browser.msie && $.browser.version <= 6 ){
15 alert('IE 6 or below version');
16 }
17
18 if ($.browser.msie && $.browser.version > 6){
19 alert('IE above 6');
20 }
21 });
The jQuery browser property allows you to determine the browser in which the webpage is running. This property
makes use of navigator.userAgent to determine the platform. As said earlier, that this property doesn't work for
Chrome. If you simply make an alert statement of navigator.userAgent in chrome then you will see Chrome and
Safari both the words in alert statement.
See live Demo and Code
Then how to detect chrome?

Well, if you have installed chrome on your machine and safari is not installed then you can use $.browser.safari
to detect chrome. As both the browsers are fully based on webkit. webkit is one of the flag of $.browser property.
It will be true for safari and chrome. But that's not a proper way to detect chrome.

Well, you need to alter the $.browser utility to support chrome. I found a good article about detecting chrome
using jQuery. Visit here.

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

Get ASP.NET Dropdown selected value


and text using jQuery
Labels: ASP.NET, jQuery, jQuery With ASP.NET
In this post, I will show you how can you get the selected value and selected text of ASP.NET Dropdown using
jQuery. Let's first declare the dropdown list and a button.
1 <asp:DropDownList ID="ddlLanguage" runat="server">
2 <asp:ListItem Text="Select" Value="0"></asp:ListItem>
3 <asp:ListItem Text="C#" Value="1"></asp:ListItem>
4 <asp:ListItem Text="VB.NET" Value="2"></asp:ListItem>
5 <asp:ListItem Text="Java" Value="3"></asp:ListItem>
6 <asp:ListItem Text="PHP" Value="4"></asp:ListItem>
7 </asp:DropDownList>
8
9 <asp:Button ID="btnGetValue" runat="server" Text="Get DropDown Value" />
jQuery provides val() method which returns value of any element. We will use the same method to get the value
of selected element in asp.net dropdown list.
1 $(document).ready(function(){
2 $("#btnGetValue").click(function()
3 {
4 alert($('#<%= ddlLanguage.ClientID %>').val());
5 return false;
6 });
7 });
Now what if you want to fetch the text of selected element? Well, jQuery provides text() method also to get text of
any element.
1 alert($('#<%= ddlLanguage.ClientID %>').text());
Oops!!! The alert message displays "Select C# VB.NET Java PHP". It is displaying text of all the element but not
of selected element. To get text of selected element, try below jQuery code
1 alert($('#<%= ddlLanguage.ClientID %> option:selected').text());
Here, we are telling jQuery to give me text of selected element of DropDown list.

Simple and cool!!!!

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

Set Max Length for ASP.NET MultiLine


Textbox using jQuery
Labels: jQuery, jQuery Code Examples, Jquery Code Snippets, jQuery Codes, jQuery Tips
ASP.NET textbox has a property called "MaxLength", which restrict the end-user from entering characters
beyond specified MaxLength. This property works like a charm for ASP.NET textbox but it does not work with
ASP.NET MultiLine textbox. In this post, I will show you how we can implement Maxlength property for ASP.NET
MultiLine textbox using jQuery. Let's first create a multiline textbox.
1 <asp:TextBox ID="txtValue" runat="server"
2 TextMode="MultiLine" Rows="10"
3 Columns="50"></asp:TextBox>
To restrict user from entering characters beyond a certain limit, we will use keypress() event of multiline textbox.
For demo purpose, I have set the maxlenght to 250. You can change as per your need.
1 $(document).ready(function()
2{
3 var MaxLength = 250;
4 $('#txtValue').keypress(function(e)
5 {
6 if ($(this).val().length >= MaxLength) {
7 e.preventDefault();}
8 });
9 });
In keypress event code, we check the lenght of text(which is already in textbox) and if the length is beyond the
maxlength variable value then it is not getting appended in the textbox. Simple and easily achieved with few lines
of code. But it would be nice, if we can show the end user that how many character are entered in the textbox.
See below image.
Well, all you need to do is to place a label below the textbox with the default text as "Allowed only 250
characters."

1 <asp:Label ID="lblCount" runat="server" Text="Allowed only 250


characters."
2 Font-Size="Smaller" Font-Names="Arial"> </asp:Label>
Now, to show how many characters end user has entered, we will use keyup() event of multiline textbox. This
event will take the count of currently entered characters in textbox and modifies the value of the label.
1 $('#txtValue').keyup(function()
2{
3 var total = parseInt($(this).val().length);

4 $("#lblCount").html('Characters entered <b>' + total + '</b> out of


250.');
5 });
Simple and cool, isn't it?

See live Demo and Code.


<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Limit characters in MultiLine Textbox Demo</title>
<script type="text/javascript"
src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js">
</script>

<script type="text/javascript">
$(document).ready(function()
{
var MaxLength = 250;
$('#txtValue').keypress(function(e)
{
if ($(this).val().length >= MaxLength) {
e.preventDefault();
}
});
$('#txtValue').keyup(function(e)
{
var total = parseInt($(this).val().length);
$("#lblCount").html('Characters entered <b>' + total + '</b> out of 250.');
});
});
</script>
</head>
<body>
<br/>
<textarea name="txtValue" rows="10" cols="50" id="txtValue"></textarea><br />
<span id="lblCount" style="font-family:Arial;font-size:Smaller;">Description should be less than 250
characters.</span>

</body>
</html>
Feel free to contact me for any help related to jQuery. I will gladly help you.

jQuery Code: Change text to


Uppercase
Labels: jQuery, jQuery Code Examples, Jquery Code Snippets, jQuery Codes

Below jQuery code change text to UPPERCASE.


1 $(document).ready(function(){
2 var strVal = 'jquery by example rocks!!'
3 alert(strVal.toUpperCase());
4 });
See live Demo and Code
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>How to Convert string to UPPERCASE Demo</title>
<script type="text/javascript"
src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js">
</script>

<script type="text/javascript">
$(document).ready(function(){
var strVal = 'jquery by example rocks!!';
alert(strVal.toUpperCase());
});
</script>
</head>
<body>
<span id="spnCursor"></span>
</body>
</html>
I have created a plugin called "Setcase" which can be used to convert text to uppercase, lowercase, title case
and pascal case. It starts converting text to case as soon as user starts typing.
Download Plugin
Feel free to contact me for any help related to jQuery. I will gladly help you.

How to scroll to the bottom of a


textarea using jQuery
Labels: jQuery, jQuery Code Examples, Jquery Code Snippets, jQuery Codes, jQuery Functions, jQuery
Methods, jQuery Tips, Methods
Today I came across a situation where in textarea control, text was appended from code behind (.NET code) on
button click. But the actual concern was that appended text is not visible to the end user as textbox area shows
text from the top.

So I looked into jQuery to find solution of it and there you go. jQuery provides a method called "scrollTop", which
allows you to set the scroll bar value within any element. Below jQuery code set the scrollTop value to the
element's scrollHeight.

scrollHeight is Height of the scroll view of an element; it includes the element padding but not its margin.
1 $(document).ready(function(){
2 $('#txtMultiLine').scrollTop($('#txtMultiLine')[0].scrollHeight);
3 });
1 &lt;textarea rows="20" cols="100" id="txtMultiLine"&gt;

And yes, one strange thing is "('#txtMultiLine').scrollHeight" doesn't work. I wonder, why? But
"('#txtMultiLine')[0].scrollHeight" works.
See live Demo and Code
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Clone method Demo</title>
<script type="text/javascript"
src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js">
</script>

<script type="text/javascript">
$(document).ready(function(){
$('#txtMultiLine').scrollTop($('#txtMultiLine')[0].scrollHeight);
});
</script>
</head>
<body>
<textarea rows="20" cols="100" id="txtMultiLine">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam consequat dictum facilisis. Fusce fermentum
vulputate ligula, ac imperdiet ligula varius sed. Sed vitae risus vitae velit pretium dapibus id vel leo. Sed sit amet
libero a elit aliquam rhoncus in vitae urna. Nullam mattis ornare porta. Curabitur luctus enim orci. Nullam placerat
interdum risus, eget dignissim orci feugiat eu. Proin ac elit quis nunc vestibulum egestas eu in ligula. Proin
tempus lacus vitae lorem molestie euismod. Integer quis tortor eu enim scelerisque rutrum. Quisque consectetur
neque non nibh tincidunt eu tristique nisi ullamcorper. In venenatis mollis rutrum. Maecenas sit amet laoreet orci.
Duis eleifend elementum nisl, non convallis neque consectetur laoreet. In eu nisi nisl. Etiam scelerisque nibh sit
amet erat rutrum mollis. Maecenas at sagittis augue. Vestibulum pellentesque volutpat augue, vel commodo
sapien auctor sit amet. Cras gravida iaculis quam, et pellentesque est congue non. Nullam a orci eu lorem mattis
ultricies mattis vitae justo.

Cras sodales, turpis ut malesuada rutrum, metus lacus molestie nibh, nec feugiat elit ante eget diam. Aenean vel
dui vel dui tristique vulputate. Integer sed elit dui, id cursus libero. Suspendisse iaculis dignissim eleifend.
Suspendisse potenti. Phasellus rutrum interdum fringilla. Vestibulum congue libero nec nisl vehicula et eleifend
neque consectetur. Suspendisse dui est, pharetra ut molestie a, lacinia id risus. Fusce sollicitudin, arcu sit amet
dictum consectetur, lacus erat ultricies risus, quis scelerisque nunc neque vel urna. Cras vel lacus eget metus
feugiat pulvinar. Integer at sem turpis, vel scelerisque ipsum. Nulla justo lacus, facilisis dignissim vestibulum id,
imperdiet a nunc. In suscipit ullamcorper odio porta accumsan. Mauris tempus hendrerit odio nec vestibulum.
Aenean rutrum nisl sed dui feugiat nec aliquam erat pellentesque. Vestibulum ante ipsum primis in faucibus orci
luctus et ultrices posuere cubilia Curae; Integer nisl quam, ullamcorper tincidunt elementum ut, convallis et purus.
Quisque nec nunc nec turpis cursus bibendum quis vehicula nisl. Duis porta, quam vitae consequat fringilla, felis
neque consectetur turpis, in tincidunt ante ligula vitae enim.

Duis elementum est a massa congue nec ullamcorper mi ornare. Nam ac mauris tellus. Aenean scelerisque nunc
quis velit volutpat semper. Morbi vulputate metus ut erat aliquet egestas. Cras vehicula elit sit amet ipsum
ullamcorper et tincidunt nisi fermentum. Aenean eu velit eget odio placerat ultrices eu nec velit. Etiam quis ante
sollicitudin orci mattis semper a et eros. Sed ut porta diam. Fusce iaculis lobortis lectus, consectetur accumsan
tortor convallis quis. Cras vitae facilisis arcu. Morbi dignissim blandit lacinia. Nunc gravida, magna et adipiscing
luctus, ipsum nibh ullamcorper orci, sed vestibulum quam ipsum id elit. Nam id mi at velit eleifend ultricies.
</textarea>
</body>
Feel free to contact me for any help related to jQuery. I will gladly help you.
</body>
</html>

Disable Cut, Copy and Paste function


for textbox using jQuery
Labels: jQuery, jQuery Code Examples, Jquery Code Snippets, jQuery Codes, jQuery Tips
Today my client asked me to disable cut, copy and paste functionality for the Textbox, which means User should
not be allowed cut or copy text from the Textbox and also to paste text within Textbox. Well, it is very easy to do
this using jQuery. All you need is to bind cut, copy and paste function to Textbox and stop the current action. See
below code.
1 $(document).ready(function(){
2 $('#txtInput').live("cut copy paste",function(e) {
3 e.preventDefault();
4 });
5 });
You can also use bind function to bind these events. Read more about bind() method here.
1 $(document).ready(function(){
2 $('#txtInput').bind("cut copy paste",function(e) {
3 e.preventDefault();
4 });
5 });
But it is suggested to use live() method. Read more about live() method here and read this article to find out the
difference between bind() and live().
See live Demo and Code.
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Disable Cut,Copy and Paste Demo</title>
<script type="text/javascript"
src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.4.min.js">
</script>

<script type="text/javascript">
$(document).ready(function(){
$('#txtInput').live("cut copy paste",function(e) {
e.preventDefault();
});
});
</script>
</head>
<body>
<br />
<span> Enter Something </span>
<input type="text" id="txtInput"/>
</body>
</html>
Feel free to contact me for any help related to jQuery. I will gladly help you.

Validate Date of Birth is not greater


than current date using jQuery
Labels: jQuery, jQuery DatePicker, jQuery UI, jQuery UI DatePicker
This is a common situation where Date of birth needs to validated against the current or today's date. I have to
implement the same functionality for my project. I have used jQuery UI datepicker control to select date and
textbox was read only, it was pretty easy to implement.

Read my series of articles about jQuery UI datepicker here.

All I needed to do is to stop datepicker control to disable dates greater than today's date. jQuery UI datepicker
control provides an option to set the max date. If its value is set to "-1d" then all the dates after current date will
be disabled.
Note: I have set the year range statically but this can be set programatically.
01 $(document).ready(function(){
02 $("#txtDate").datepicker(
03 {
04 yearRange:
05 '<%=(System.DateTime.Now.Year - 150).ToString()%>:
06 <%=System.DateTime.Now.Year.ToString() %>',
07 changeMonth:true,
08 changeYear:true,
09 maxDate: '-1d'
10 });
11 });
See live Demo and Code.
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Date of Birth Validation in Datepicker</title>
<link type="text/css" rel="Stylesheet"href="http://ajax.microsoft.com/ajax/jquery.ui/1.8.5/themes/start/jquery-
ui.css" />
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</script>
<script type="text/javascript"
src="http://ajax.microsoft.com/ajax/jquery.ui/1.8.5/jquery-ui.min.js">
</script>

<script type="text/javascript">
$(document).ready(function(){
var d = new Date();
var curr_year = d.getFullYear();
$("#txtDate").datepicker(
{ yearRange: '1900:'+ curr_year, changeMonth:true, changeYear:true, maxDate: '-1d'});
});
</script>
</head>
<body>
Select Date: <input type="text" id="txtDate" readonly = "readonly" />
</body>
</html>
Read my series of articles about jQuery UI datepicker here.

How to display ToolTip on jQuery UI


Datepicker for specific dates
Labels: Date Picker, jQuery, jQuery DatePicker, jQuery UI, jQuery UI DatePicker
I had already posted about how to "Highlight Specific Dates in jQuery UI Datepicker". Yesterday one of my
blog reader asked me that how to show any description or tool tip on the highlighted date in jQuery UI
Datepicker.Would it be possible? I provided him the solution and thought of sharing with you as well.
To highlight a date(s), it is important to apply some kind of style so that it looks different from others dates. So
define a CSS class, which will be used to show highlighted dates.
1 //Code Starts
2 .Highlighted a{
3 background-color : Green !important;
4 background-image :none !important;
5 color: White !important;
6 font-weight:bold !important;
7 font-size: 12pt;
8}
9 //Code Ends
First, create an array of dates which should be highlighted. In the below jQuery code, you will see the array index
value is also a date object and the value is also a date object. And also create another array, which will contain
text that you want to show as tooltip.
01 //Code Starts
02 var SelectedDates = {};
03 SelectedDates[new Date('04/05/2012')] = new Date('04/05/2012');
04 SelectedDates[new Date('05/04/2012')] = new Date('05/04/2012');
05 SelectedDates[new Date('06/06/2012')] = new Date('06/06/2012');
06
07 var SeletedText = {};
08 SeletedText[new Date('04/05/2012')] = 'Holiday1';
09 SeletedText[new Date('05/04/2012')] = 'Holiday2';
10 SeletedText[new Date('06/06/2012')] = 'Holiday3';
11 //Code Ends
Now, the DatePicker control provide "beforeShowDay" event, which gets called before building the control. So
use this event to highlight the date. Get the highlighted date and text from both the arrays.
01 //Code Starts
02 $('#txtDate').datepicker({
03 beforeShowDay: function(date)
04 {
05 var Highlight = SelectedDates[date];
06 var HighlighText = SeletedText[date];
07 if (Highlight) {
08 return [true, "Highlighted", HighlighText];
09 }
10 else {
11 return [true, '', ''];
12 }
13 }
14 });
15 //Code Ends
So the complete code is,
01 //Code Starts
02 $(document).ready(function() {
03 var SelectedDates = {};
04 SelectedDates[new Date('04/05/2012')] = new Date('04/05/2012');
05 SelectedDates[new Date('05/04/2012')] = new Date('05/04/2012');
06 SelectedDates[new Date('06/06/2012')] = new Date('06/06/2012');
07
08 var SeletedText = {};
09 SeletedText[new Date('04/05/2012')] = 'Holiday1';
10 SeletedText[new Date('05/04/2012')] = 'Holiday2';
11 SeletedText[new Date('06/06/2012')] = 'Holiday3';
12
13 $('#txtDate').datepicker({
14 beforeShowDay: function(date) {
15 var Highlight = SelectedDates[date];
16 var HighlighText = SeletedText[date];
17 if (Highlight) {
18 return [true, "Highlighted", HighlighText];
19 }
20 else {
21 return [true, '', ''];
22 }
23 }
24 });
25 });
26 //Code Ends
See result below.

How to Zoom an image using jQuery


Labels: jQuery, jQuery Code Examples, Jquery Code Snippets, jQuery Codes, jQuery Functions, jQuery
Methods, Methods
You must had seen the zoom in and zoom out functionality for images on many sites. We can very easily achieve
the Zoom In and Zoom Out functionality using jQuery toggle method. It is really simple. Let me first tell you the
logic behind the implementation. Initially when document is ready then we will set the width of the image and after
that on click of the image we will change the width of the image with some animation (Zoom In) and reset the
width on alternate click (Zoom Out). Let's directly go to the point.

Place an image on the page.


1 <h1>Click image to Zoom In and Zoom Out</h1>
2 <img src="Images/smile.png" alt="Smile" id="imgSmile" />
Now jQuery code.
01 $(document).ready(function(){
02 $('#imgSmile').width(200);
03 $('#imgSmile').mouseover(function()
04 {
05 $(this).css("cursor","pointer");
06 });
07 $("#imgSmile").toggle(function()
08 {$(this).animate({width: "500px"}, 'slow');},
09 function()
10 {$(this).animate({width: "200px"}, 'slow');
11 });
12 });
Let's understand the code.
Initially we have set the image width to 200px and on mouseover event, mouse cursor is changed to pointer. So it
gives an impression that image is clickable.

As in the above code, toggle method is used. toggle method binds two or more handlers to the element, which
will be executed on click. If two handlers are specified then on first click first handler will be called and on second
click second handler will be called. Toggle method internally makes a call to click event only.

So in our code, when first time is click width is increased to 500 px and on second click width is reset to 200 px.
Animate function is also used to show zooming effect in animated manner. To use animate, we need to pass
CSS properties to be set and the timespan. Timespan value can be in milliseconds or one of the string values
from 'slow', 'normal' or 'fast'.
See live Demo and Code.
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>How to Zoom an Image Demo</title>
<script type="text/javascript"
src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js">
</script>

<script type="text/javascript">
$(document).ready(function(){
$('#imgSmile').width(200);
$('#imgSmile').mouseover(function()
{
$(this).css("cursor","pointer");
});
$("#imgSmile").toggle(function()
{$(this).animate({width: "500px"}, 'slow');},
function()
{$(this).animate({width: "200px"}, 'slow');
});
});
</script>
</head>
<body>
<h1>Click image to Zoom In and Zoom Out</h1>
<br />
<img src="http://2.bp.blogspot.com/_pP4JIb2v5LA/TH9nWQ4VwCI/AAAAAAAABTQ/PFM1X6LB-
ug/s1600/Smiley.png" alt="smile" id="imgSmile"></img>
</body>
</html>
Feel free to contact me for any help related to jQuery. I will gladly help you.

How to Zoom image on mouseover


using jQuery
Labels: jQuery, jQuery Code Examples, Jquery Code Snippets, jQuery Codes, jQuery Functions, jQuery
Methods, Methods
I had already posted about Zoom an image using jQuery but that is on click event of the button. One of my
reader asked me how to zoom an image with out a click, simply when mouse is on image. This is not a tough
task to do. jQuery provides 2 events mouseover() and mouseout() and as name suggest, these events are
executed on mouse moves. To achieve the zoom in effect on mouse over, one need to animate the image using
these 2 events. See below code.
1 $('#imgSmile').width(200);
2 $('#imgSmile').mouseover(function()
3{
4 $(this).css("cursor","pointer");
5 $(this).animate({width: "500px"}, 'slow');
6 });
In above code, when mouse is over the image, then the width of image is set to 500 pixels where originally it is
200px.
And on mouse out, just set the width back to 200px. Simple..
1 $('#imgSmile').mouseout(function()
2{
3 $(this).animate({width: "200px"}, 'slow');
4 });
See live Demo and Code
<h1>Move mouse on image to Zoom In and Zoom Out</h1>
<br />
<img src="http://2.bp.blogspot.com/_pP4JIb2v5LA/TH9nWQ4VwCI/AAAAAAAABTQ/PFM1X6LB-
ug/s1600/Smiley.png" alt="smile" id="imgSmile"></img>

$(document).ready(function(){
$('#imgSmile').width(200);
$('#imgSmile').mouseover(function()
{
$(this).css("cursor","pointer");
$(this).animate({width: "500px"}, 'slow');
});

$('#imgSmile').mouseout(function()
{
$(this).animate({width: "200px"}, 'slow');
});
});
Feel free to contact me for any help related to jQuery, I will gladly help you.

Don't forget to read:


How to zoom element text on
Mouseover using jQuery
Labels: jQuery, jQuery Code Examples, Jquery Code Snippets, jQuery Codes
For one of my requirement, I need to zoom in the text of div element on mouseover and zoom out on mouseout.
This was fairly simple with jQuery so I thought to share with you. For example, you want to zoom in the text
placed in a div with ID "Content". The default style applied to "Content" div element is below.
1 #content
2{
3 font-size:10pt;
4 font-family:Arial,sans-serif;
5}
On jQuery side, you need to do following things.
1. Fetch the existing size of the element and store it in any variable.
2. Double the existing size and store in another variable.
3. Set the font size to doubled size on mouseover event of element.
4. Set the font size to original size on mouseover event of element.
That's it. See jQuery code below.
01 $(document).ready(function() {
02 var oldSize = parseFloat($("#content").css('font-size'));
03 var newSize = oldSize * 2;
04 $("#content").hover(
05 function() {
06 $("#content").animate({ fontSize: newSize}, 200);
07 },
08 function() {
09 $("#content").animate({ fontSize: oldSize}, 200);
10 }
11 );
12 });
Rather than using mouseover and mouseout method seperately, jQuery provides another method named
"hover()" which serves purpose of both the methods. Please read more here about hover().
See live Demo and Code.
<div id="content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec pharetra pharetra dignissim. Aenean
vestibulum elementum varius. Suspendisse tempus, tortor eget adipiscing volutpat, justo lacus
vestibulum sapien, nec porta libero tortor elementum augue. Pellentesque sit amet est et tortor
ultricies tempor. Donec facilisis dui placerat diam hendrerit congue. Vivamus nec risus metus, eget
fermentum ipsum. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis
egestas.
</div>

#content
{
font-size:10pt;
font-family:Arial,sans-serif;
}

$(document).ready(function() {
var oldSize = parseFloat($("#content").css('font-size'));
var newSize = oldSize * 2;
$("#content").hover(
function() {
$("#content").animate({ fontSize: newSize}, 200);
},
function() {
$("#content").animate({ fontSize: oldSize}, 200);
}
);
});

jQuery code to allow only numbers in


textbox
Labels: jQuery, jQuery Code Examples, Jquery Code Snippets, jQuery Codes
Below jQuery code snippets will allow only numbers in the textbox. However backspace and delete keys are also
allowed.
01 $(document).ready(function(){
02 $("#<%= txtNumbers.ClientID%>").keydown(function(event) {
03 if(event.shiftKey)
04 event.preventDefault();
05 if (event.keyCode == 46 || event.keyCode == 8) {
06 }
07 else {
08 if (event.keyCode < 95) {
09 if (event.keyCode < 48 || event.keyCode > 57) {
10 event.preventDefault();
11 }
12 }
13 else {
14 if (event.keyCode < 96 || event.keyCode > 105) {
15 event.preventDefault();
16 }
17 }
18 }
19 });
20 });
See live Demo and Code
<input type="text" id="txtNumbers" />

$(document).ready(function(){
$("#txtNumbers").keydown(function(event) {
if(event.shiftKey)
{
event.preventDefault();
}

if (event.keyCode == 46 || event.keyCode == 8) {
}
else {
if (event.keyCode < 95) {
if (event.keyCode < 48 || event.keyCode > 57) {
event.preventDefault();
}
}
else {
if (event.keyCode < 96 || event.keyCode > 105) {
event.preventDefault();
}
}
}
});
});

jQuery code to allow numbers and


arrow keys in textbox
Labels: jQuery, jQuery Code Examples, Jquery Code Snippets, jQuery Codes
I have already posted about "jQuery code to allow only numbers in textbox", but one of my reader asked me to
allow arrow keys as well. I have modified the code slightly to allow arrow keys. I thought it's good idea to share
with all my readers. See below jQuery code.
01 $(document).ready(function(){
02 $("#txtNumbers").keydown(function(event) {
03 if(event.shiftKey)
04 event.preventDefault();
05 if (event.keyCode == 46 || event.keyCode == 8) {
06 }
07 else {
08 if (event.keyCode < 95) {
09
10 if (event.keyCode < 48 || event.keyCode > 57) {
11 if (event.keyCode >= 37 && event.keyCode <= 40) {
12 }
13 else
14 {
15 event.preventDefault();
16 }
17 }
18 }
19 else {
20 if (event.keyCode < 96 || event.keyCode > 105) {
21 event.preventDefault();
22 }
23 }
24 }
25 });
26 });
See live Demo and Code.
<input type="text" id="txtNumbers" onpaste="return false;" />
$(document).ready(function(){
$("#txtNumbers").keydown(function(event) {
if(event.shiftKey)
event.preventDefault();
if (event.keyCode == 46 || event.keyCode == 8) {
}
else {
if (event.keyCode < 95) {

if (event.keyCode < 48 || event.keyCode > 57) {


if (event.keyCode >= 37 && event.keyCode <= 40) {
}
else
{
event.preventDefault();
}
}
}
else {
if (event.keyCode < 96 || event.keyCode > 105) {
event.preventDefault();
}
}
}
});
});
Also read my related posts, which describe how to allow alphabets, numbers and specific characters.
jQuery code to allow numbers, alphabets or specific characters
Feel free to contact me for any help related to jQuery, I will gladly help you.

Also read my related posts, which describe how to allow arrow keys with number, alphabets and specific
characters.
jQuery code to allow numbers and arrow keys in textbox
jQuery code to allow numbers, alphabets or specific characters
Feel free to contact me for any help related to jQuery. I will gladly help you.

jQuery code to allow numbers,


alphabets or specific characters
Labels: jQuery, jQuery Code Examples, Jquery Code Snippets, jQuery Codes, jQuery Plugins
There is a general requirement in many projects where for certain fields or input only numeric, alphabets, specific
character or set of characters must be allowed. For example, When you are requesting input for Phone number
or Zip code from the end-user, then you don't want to allow user to enter any alphabets.

There are plenty of jQuery plugins available that satisfy your requirement where you want to restrict user to enter
only numbers.

Many times, we write lots of code to achieve such functionality. But we live in an era where plenty of plugins are
available then why to rewrite where same thing already exists. That's why there are plugins. I always believe it is
a better choice to use existing code or plugin rather than coding it again.

While searching, I found a jQuery plugin called "AlphaNumeric" and it really caught my attention as I found this
very useful.

The beauty of this plugin is that it has some standard methods that allows only numeric, alphabets and
alphanumeric character but other than that you can also set which other characters you want to allow. As for
example, for phone number, other than 0-9 you also want to allow user to enter "-" or space. You can set this
very easily.

This plugin has 3 standard methods.


1. numeric : Allows only numeric characters.
2. alpha : Allows only alphabets
3. alphanumeric : Allow alphabets and numeric characters.

Other than these standard methods, this plugin comes with properties.
1. allow : Specify which other characters you want to allow.
2. ichras : Specify characters that needs to be prevented.
3. allcaps : Only uppercase characters are allowed.
4. nocaps : Only lowercaps characters are allowed.

Code Samples:

To allow only numbers:


1 $('#txtNum').numeric();
To allow only alphabets:
1 $('#txtAlpha').alpha();
To allow only numbers and alphabets:
1 $('#txtNum').alphanumeric();
Allow only numeric characters, and some other characters like dot,comma (.,)
1 $('#txtNum').numeric({allow:".,");
See live Demo and Code
Also read my other post, which describe how to allow arrow keys with number.
jQuery code to allow numbers and arrow keys in textbox
Feel free to contact me for any help related to jQuery. I will gladly help you.

Determine which key was pressed


using jQuery
Labels: jQuery, jQuery Code Examples, Jquery Code Snippets, jQuery Codes, jQuery Events, jQuery
Functions, jQuery Methods, Methods
I had a requirement where I need to check which key was pressed by the User in the textbox and then take
various action. So below is simple jQuery code to determine or find out which key was pressed. We are using
keypress() event of jQuery to detect which key was pressed.
1 <input type='text' id='txtValue' />
2 <span id="spn">You have typed: </span>
Below jQuery code first detects the keyCode and then it converts into the character. event.keyCode will give you
the ASCII value of the pressed key but if you want to show the entered character then using
String.fromCharCode() method, you can get the character.
1 $(document).ready(function(){
2 $('#txtValue').keypress(function(event){
3 var txt = $('#spn').text();
4 $('#spn').text(txt + String.fromCharCode(event.keyCode));
5 });
6 });
See live Demo and Code.
<input type='text' id='txtValue' />
<br/>
<br/>
<span id="spn">You have typed: </span>
$(document).ready(function(){
$('#txtValue').keypress(function(event){
var txt = $('#spn').text();
$('#spn').text(txt + String.fromCharCode(event.keyCode));
});
});
Feel free to contact me for any help related to jQuery, I will gladly help you.

How to Disable Spacebar in text box


using jQuery
Labels: jQuery, jQuery Code Examples, Jquery Code Snippets, jQuery Codes, jQuery Tips
For one of my requirement, I need to restrict/disable end-user to enter space in the input field or textbox. This
was piece of cake with jQuery. All I need to do is to check the keycode of spacebar and restrict its default action
on keydown event. See below jQuery code. "txtNoSpaces" is the name of the textbox.
1 $(document).ready(function(){
2 $("#txtNoSpaces").keydown(function(event) {
3 if (event.keyCode == 32) {
4 event.preventDefault();
5 }
6 });
7 });
See live Demo and Code.
<input type="text" id="txtNoSpaces" onpaste="return false;" />

$(document).ready(function(){
$("#txtNoSpaces").keydown(function(event) {
if (event.keyCode == 32) {
event.preventDefault();
}
});
});
Also read,
jQuery code to allow only numbers in textbox
jQuery code to allow numbers and arrow keys in textbox
Restrict Shift Key using jQuery

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

Useful jQuery code examples for


ASP.NET Controls
Labels: ASP.NET, jQuery, jQuery Code Examples, Jquery Code Snippets, jQuery Codes, jQuery
Tips, jQuery With ASP.NET
In this post, you will see list of some 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. Get label value:
1 $('#<%=Label1.ClientID%>').text();
Set label value:
1 $('#<%=Label1.ClientID%>').text("New Value");
Get Textbox value:
1 $('#<%=TextBox1.ClientID%>').val();
Set Textbox value:
1 $('#<%=TextBox1.ClientID%>').val("New Value");
Get Dropdown value:
1 $('#<%=DropDownList1.ClientID%>').val();
Set Dropdown value:
1 $('#<%=DropDownList1.ClientID%>').val("New Value");
Get text of selected item in dropdown:
1 $('#<%=DropDownList1.ClientID%> option:selected').text();
Get Checkbox Status:
1 $('#<%=CheckBox1.ClientID%>').attr('checked');
Check the Checkbox:
1 $('#<%=CheckBox1.ClientID%>').attr('checked',true);
Uncheck the Checkbox:
1 $('#<%=CheckBox1.ClientID%>').attr('checked',false);
Get Radiobutton Status:
1 $('#<%=RadioButton1.ClientID%>').attr('checked');
Check the RadioButton:
1 $('#<%=RadioButton1.ClientID%>').attr('checked',true);
Uncheck the RadioButton:
1 $('#<%=RadioButton1.ClientID%>').attr('checked',false);
Disable any control:
1 $('#<%=TextBox1.ClientID%>').attr('disabled', true);
Enable any control:
1 $('#<%=TextBox1.ClientID%>').attr('disabled', false);
Make textbox read only:
1 $('#<%=TextBox1.ClientID%>').attr('readonly', 'readonly');
Share your useful code as well (via commenting), I will add this into this list.

jQuery to Retrieve Server's current


date and time with ASP.NET
Labels: ASP.NET, jQuery, jQuery Code Examples, Jquery Code Snippets, jQuery Codes, jQuery With ASP.NET
In this post, we will see how to retrieve server's current date and time without using ajax. It's very simple and one
line of ASP.NET code can help you to retrieve the server's current date & time. For demo, I have placed a
textbox and will fetch the Server's date and time and display it in Textbox.
1 <asp:TextBox ID="txtValue" runat="server"></asp:TextBox>
See below jQuery code.
1 $(document).ready(function() {
2 $('#txtValue').val('<%=(System.DateTime.Now).ToString()%>');
3 });
It is just a simple ASP.NET code, which we normally write in code behind file.Above code will provide date and
time both. If you want to fetch only time, then modify the above jQuery code to below code.
1 $(document).ready(function() {
2 $('#txtValue').val('<%=System.DateTime.Now.ToShortTimeString()%>');
3 });
You can also fetch only the Year, month, day, hours, minutes or seconds. For example, to fetch hours,
1 $('#txtValue').val('<%=(System.DateTime.Now.Hour).ToString()%>');
To fetch only minutes,
1 $('#txtValue').val('<%=(System.DateTime.Now.Minute).ToString()%>');
Read more about DateTime.Now on MSDN and find out what more you can achieve using this property.

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

Validate email address using jQuery


Labels: jQuery, jQuery Code Examples, Jquery Code Snippets, jQuery Codes
This is a very basic functionality to validate the email address. In this post, I will show you how
to validatethe email address using jQuery. To validate the email address, I have created a separate function
which based on email address, returns true or false. Email address validation is done using regular expression.
01 function validateEmail(txtEmail){
02 var a = document.getElementById(txtEmail).value;

03 var filter = /^((\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-


.]\w+)*?)\s*;?\s*)+/;
04 if(filter.test(a)){
05 return true;
06 }
07 else{
08 return false;
09 }
10 }
One just need to make a call to this function to validate the email address. For demo, I have used on blur event of
textbox. But It can be used on click on button or any another event.
01 $(document).ready(function() {
02 $('#txtEmail').blur(function() {
03 if(validateEmail('txtEmail'))
04 {
05 alert('Email is valid');
06 }
07 else
08 {
09 alert('Invalid Email Address');
10 }
11 });
12 });
See live Demo and Code
Email Address: <input type='text' id='txtEmail'/>

body
{
padding: 10px;
font-family: Arial;
Font-size: 10pt;
}

$(document).ready(function() {
$('#txtEmail').blur(function() {
if(validateEmail('txtEmail'))
{
alert('Email is valid');
}
else
{
alert('Invalid Email Address');
}
});
});
function validateEmail(txtEmail){
var a = document.getElementById(txtEmail).value;
var filter = /^((\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*?)\s*;?\s*)+/;
if(filter.test(a)){
return true;
}
else{
return false;
}
}
Feel free to contact me for any help related to jQuery, I will gladly help you.

How to Set focus on First textbox of


page using jQuery
Labels: jQuery, jQuery Code Examples, Jquery Code Snippets, jQuery Codes, jQuery Tips
In any webpage where there are lots of input controls and you want the foucs on the first text box when the page
is loaded. It is a piece of cake with jQuery. See below code.
1 $(document).ready(function() {
2 $('input:text:first').focus();
3 });
See live Demo and Code.
First Name : <input type='text' id='txtFirstName' /> <br/><br/>
Last Name : <input type='text' id='txtLastName' /><br/><br/>
Age : <input type='text' id='txtAge' /><br/><br/>

<input type='button' id='btnSubmit' Value =' Submit'/>

$(document).ready(function() {
$('input:text:first').focus();
});

But there could be one problem with this approach, if you first textbox is disabled. Well, again piece of cake with
jQuery.
1 $(document).ready(function() {
2 $('input[type=text]:enabled:first').focus();
3 });
See live Demo and Code.
First Name : <input type='text' id='txtFirstName' disabled='disabled'/> <br/><br/>
Last Name : <input type='text' id='txtLastName' /><br/><br/>
Age : <input type='text' id='txtAge' /><br/><br/>

<input type='button' id='btnSubmit' Value =' Submit'/>

$(document).ready(function() {
$('input[type=text]:enabled:first').focus();
});
Cool, isn't it. Another problem, my first textbox is not visible (display:none) then what should I do?
1 <input type='text' id='txtFirstName' style='display:none' />
Not to worry, as we have jQuery. :)
1 $(document).ready(function() {
2 $('input[type=text]:visible:first').focus();
3 });
See live Demo and Code.
First Name : <input type='text' id='txtFirstName' style='display:none' /> <br/><br/>
Last Name : <input type='text' id='txtLastName' /><br/><br/>
Age : <input type='text' id='txtAge' /><br/><br/>

<input type='button' id='btnSubmit' Value =' Submit'/>

$(document).ready(function() {
$('input[type=text]:visible:first').focus();
});
The best method is to set the focus using ID of the control as you know that control is visible and it is not
disabled.
1 $(document).ready(function() {
2 $('#txtFirstName').focus();
3 });
Feel free to contact me for any help related to jQuery, I will gladly help you.

Get total count of textboxes using


jQuery
Labels: jQuery, jQuery Code Examples, Jquery Code Snippets, jQuery Codes
Today,One of my colleague asked me that how to get total number of textbox count using jQuery. This was fairly
simple. You can use the length property to get count of textbox. See below jQuery code.
1 $(document).ready(function() {
2 alert($("input:text").length);
3 });
In this jQuery code, first selecting all the textbox and then taking it's length to get count of total number of
textboxes.
See live Demo and Code.
First Name : <input type='text' id='txtFirstName' /> <br/><br/>
Last Name : <input type='text' id='txtLastName' /><br/><br/>
Age : <input type='text' id='txtAge' /><br/><br/>

$(document).ready(function() {
alert($("input:text").length);
});
Feel free to contact me for any help related to jQuery, I will gladly help you.

How to set focus on next textbox on


Enter Key using jQuery
Labels: jQuery, jQuery Code Examples, Jquery Code Snippets, jQuery Codes
I had already posted about "How to Set focus on First textbox of page using jQuery",
but there was a situation where I need to move to next textbox using Enter key. Normally, tab key is
used to move to next text box and by default, when Enter key is pressed, the form gets submitted or it
calls the default button click event. But it would be a nice feature for end-user to give him ability to
move to next textbox using Enter key.

As I always say "Not to worry, when we have jQuery". This can be done with jQuery as well. First see
the jQuery code.
01 $(document).ready(function() {
02 $('input:text:first').focus();
03
04 $('input:text').bind("keydown", function(e) {
05 var n = $("input:text").length;
06 if (e.which == 13)
07 { //Enter key
08 e.preventDefault(); //Skip default behavior of the enter key
09 var nextIndex = $('input:text').index(this) + 1;
10 if(nextIndex < n)
11 $('input:text')[nextIndex].focus();
12 else
13 {
14 $('input:text')[nextIndex-1].blur();
15 $('#btnSubmit').click();
16 }
17 }
18 });
19
20 $('#btnSubmit').click(function() {
21 alert('Form Submitted');
22 });
23 });
Explanation:
The document.ready() when gets executed then it first set the focus to the very first textbox of the
page using "$('input:text:first').focus();". Read How to Set focus on First textbox of page
using jQuery. There is a keydown function which is binded to all the textbox using bind metohd.
Read more about bind. If you are using ajax, then don't use bind use live method. Read about live.

Now, the keydown function, first find the total number of textboxes in the page. Read Get total count
of textboxes using jQuery.
1 var n = $("input:text").length;
Then, it check whether entry key is pressed If Yes, then prevent its default behavior. Take the index of
next textbox and assign it to nextIndex variable.
1 var nextIndex = $('input:text').index(this) + 1;
After that it checks whether nextIndex is less than the total count of textbox. If Yes, then it sets the
focus to next textbox and if not, then it removes the focus from current textbox and set for "Submit
button".
1 if(nextIndex < n)
2 $('input:text')[nextIndex].focus();
3 else
4{
5 $('input:text')[nextIndex-1].blur();
6 $('#btnSubmit').click();
7}
Simple and really cool functionality.
See live Demo and Code.

How to set focus on next textbox on


Enter Key using jQuery
Labels: jQuery, jQuery Code Examples, Jquery Code Snippets, jQuery Codes
I had already posted about "How to Set focus on First textbox of page using jQuery", but there was a
situation where I need to move to next textbox using Enter key. Normally, tab key is used to move to next text
box and by default, when Enter key is pressed, the form gets submitted or it calls the default button click event.
But it would be a nice feature for end-user to give him ability to move to next textbox using Enter key.

As I always say "Not to worry, when we have jQuery". This can be done with jQuery as well. First see the jQuery
code.
01 $(document).ready(function() {
02 $('input:text:first').focus();
03
04 $('input:text').bind("keydown", function(e) {
05 var n = $("input:text").length;
06 if (e.which == 13)
07 { //Enter key
08 e.preventDefault(); //Skip default behavior of the enter key
09 var nextIndex = $('input:text').index(this) + 1;
10 if(nextIndex < n)
11 $('input:text')[nextIndex].focus();
12 else
13 {
14 $('input:text')[nextIndex-1].blur();
15 $('#btnSubmit').click();
16 }
17 }
18 });
19
20 $('#btnSubmit').click(function() {
21 alert('Form Submitted');
22 });
23 });
Explanation:
The document.ready() when gets executed then it first set the focus to the very first textbox of the page using
"$('input:text:first').focus();". Read How to Set focus on First textbox of page using jQuery. There is a
keydown function which is binded to all the textbox using bind metohd. Read more about bind. If you are using
ajax, then don't use bind use live method. Read about live.

Now, the keydown function, first find the total number of textboxes in the page. Read Get total count of
textboxes using jQuery.
1 var n = $("input:text").length;
Then, it check whether entry key is pressed If Yes, then prevent its default behavior. Take the index of next
textbox and assign it to nextIndex variable.
1 var nextIndex = $('input:text').index(this) + 1;
After that it checks whether nextIndex is less than the total count of textbox. If Yes, then it sets the focus to next
textbox and if not, then it removes the focus from current textbox and set for "Submit button".
1 if(nextIndex < n)
2 $('input:text')[nextIndex].focus();
3 else
4{
5 $('input:text')[nextIndex-1].blur();
6 $('#btnSubmit').click();
7}
Simple and really cool functionality.
See live Demo and Code.
First Name : <input type='text' id='txtFirstName' /> <br/><br/>
Last Name : <input type='text' id='txtLastName' /><br/><br/>
Age : <input type='text' id='txtAge' /><br/><br/>

<input type='button' id='btnSubmit' Value =' Submit'/>

$(document).ready(function() {
$('input:text:first').focus();

$('input:text').bind("keydown", function(e) {
var n = $("input:text").length;
if (e.which == 13)
{ //Enter key
e.preventDefault(); //to skip default behavior of the enter key
var nextIndex = $('input:text').index(this) + 1;
if(nextIndex < n)
$('input:text')[nextIndex].focus();
else
{
$('input:text')[nextIndex-1].blur();
$('#btnSubmit').click();
}
}
});

$('#btnSubmit').click(function() {
alert('Form Submitted');
});
});
Feel free to contact me for any help related to jQuery, I will gladly help you.

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

How to Replace Text On Page using


jQuery
Labels: jQuery, jQuery Code Examples, Jquery Code Snippets, jQuery Codes
Today, for one of my requirement, I have to replace all the (.)dots in my page with "---". The basic idea find all the
(.) in HTML and replace them with "---". This can be done very easily with jQuery. First you replace the (.) with "---
" and assign it to any variable then you need to assign back that value to HTML of the page. See below code.
1 $(document).ready(function() {
2 var strNewString = $('body').html().replace(/\./g,'---');
3 $('body').html(strNewString);
4 });
Instead of, (.) or "---", text can be anything. All you need is to make change in the replace function arguments and
you are good to go.
See live Demo and Code.
<div>

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam consectetur tortor luctus enim
consequat et pulvinar dui pharetra. Pellentesque nunc nisi, suscipit et porta a, suscipit nec dui.
Curabitur fermentum, enim ut pharetra faucibus, turpis ipsum dignissim magna, et varius urna purus ut
erat. Proin tristique nisl quis augue congue pellentesque. Donec convallis, urna vitae condimentum
lobortis, nulla quam sodales magna, eget tincidunt eros dolor vel leo. Donec eu lectus ut libero
tincidunt tempor eu vitae magna. Nunc eget diam odio, sed semper est. Praesent mollis, metus nec
iaculis auctor, lectus quam feugiat dolor, at feugiat mauris neque ac libero. Nam ut augue neque. In
in odio eget magna mollis adipiscing. Vivamus commodo odio eu eros convallis sit amet ultrices purus
rhoncus. Vivamus mauris tortor, viverra nec eleifend in, porttitor quis purus. Nunc nisl libero,
euismod vel elementum a, mattis ac felis. Aenean non eros nulla, eu tristique justo. Aliquam nec neque
sed purus faucibus varius. Sed felis lorem, feugiat ut feugiat blandit, pharetra sit amet lacus.
</div>

<p>
Vestibulum magna lacus, fermentum id fermentum quis, euismod eu mi. Sed tristique auctor elit nec
consectetur. Sed elit augue, pellentesque at iaculis id, posuere nec mauris. Donec tristique pulvinar
consectetur. Etiam congue ullamcorper est. Pellentesque eget est nibh, in varius sem. Sed eu elit
diam, vel pretium est. In fringilla tincidunt velit, id faucibus turpis volutpat ut. Integer sit amet
neque ante. Vivamus quam lacus, rhoncus sit amet dapibus a, ornare quis sapien. Suspendisse lobortis
luctus purus, ut egestas tellus bibendum ut. Sed elementum blandit eros.
</p>

$(document).ready(function() {
var strNewString = $('body').html().replace(/\./g,'---');
$('body').html(strNewString);
});

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

How to put link on image using jQuery


Labels: jQuery, jQuery Code Examples, Jquery Code Snippets, jQuery Codes, jQuery Tips
To put link of the image, we normally use <a> tag that contains image tag to show the image. But assume there
are 100 images and you need same link for every single image. Putting 100 <a> tag with each image is time
consuming and cumbersome. It would be nice if single <a> tag can be used for all the images and put the <a>
tag dynamically. Well, no worry when there is jQuery.

jQuery provides a method named "wrap()", which can be used to insert any HTML structure in set of matched
elements. In simple words, if you want put wrapper around your div element then you can use wrap() method. For
example, you have a div with ID "Child".
1 <div id="Child"></div>
And want to wrap this div with any parent then you can use "wrap()" method to insert HTML.
1 $('#Child').wrap('<div id="Parent"></div>');
Output:
1 <div id="parent">
2 <div id="child"></div>
3 </div>
Same way, we will use the wrap() method to insert hyperlink to image tag so that the image becomes clickable.
See below.
1 $(document).ready(function() {
$("#imgLogo").wrap('<a
2
href="http://jquerybyexample.blogspot.com/"></a>');
3 });
In this example, I have used ID as selector but you can use class selector to find all the images with same class
and then wrap them with <a> tag. You can also assign target="_blank" in the above <a> tag to open the link in
new window.
See live Demo and Code.
<img id="imgLogo"
src="http://static.jquery.com/files/rocker/images/logo_jquery_215x53.gif" alt="jQuery By Example" />

body
{
background-color:black;
}

$(document).ready(function() {
$("#imgLogo").wrap('<a href="http://jquerybyexample.blogspot.com/" target="_blank"></a>');
});
Also read, "How to Zoom image on mouseover using jQuery".

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

Check/Uncheck All Checkboxes with


JQuery
Labels: ASP.NET, jQuery, jQuery Functions, jQuery Methods, jQuery With ASP.NET, Methods
This particular article is about a pretty common functionality which I think most of the software engineers face in
their projects. Even I came across the same situation many times. Previously I used to achieve the functionality
via JavaScript, which really worked flawlessly. But as a software engineer, I think one should always adapt the
new technology. So, this time I tried to achieve the same via JQuery as its booming now and one need to
upgrade himself. So what functionality are we talking about? See below given image.

Okay. So you must have got the idea about the functionality. Yes, you guessed it right. It’s about selecting all the
items of checkbox list, when select all is checked. You can find thousands of solution using Jquery when you
google it. Then why you are here. Well, in fact I googled a lot but didn’t even come across to a single article
which solves my purpose. Let me explain the requirement of the functionality here.
1. When “Select All” checkbox is checked, it must change the status of all the items of the
checkbox list as per “Select All” status. For e.g., if “Select All” is true then all the items of the checkbox
list must be set to true or vice versa. See Image 2.
Image 2

2. Assume, “Select All” is true and all the items of the checkbox list are also true. But when I
uncheck any item of checkbox list, it must also uncheck the select all button. See Image 3.
Image 3
3. Assume, “Select All” is unchecked. And one of the items in the checkbox list is also unchecked.
But now when I check the checkbox list item, then “Select All” must be checked. As all the items in the
checkbox list are checked.
So let’s go directly to the code.
Prerequisite:
I assume that you know the basics of JQuery. Read this article for information on Introduction to JQuery
01 <table cellpadding="2" cellspacing="2" width="50%">
02 <tr>
03 <th align="left" style="font-family:Arial;">
04 <h3>
05 Checkbox Select All Demo using JQuery</h3>
06 </th>
07 </tr>
08 <tr>
09 <td>
&nbsp;<asp:CheckBox ID="chkSelectAll" runat="server" Text="Select
10
All" Font-Size="9pt"
11 Font-Names="Arial" />
12 </td>
13 </tr>
14 <tr>
15 <td>
<asp:CheckBoxList ID="chkItems" runat="server" Width="200px" Font-
16
Size="9pt" Font-Names="Arial"
17 BorderStyle="Solid" BorderColor="Black" BorderWidth="1px">
18 </asp:CheckBoxList>
19 </td>
20 </tr>
21 </table>
Well, I have placed a checkbox “Select All” with ID “chkSelectAll” and a checkbox list with ID “chkItems”.
01 <script type="text/javascript">
02 $(document).ready(function() {
03 $("#<%=chkSelectAll.ClientID %>").click(function() {
04 $("#<%= chkItems.ClientID %>
input:checkbox").attr('checked',this.checked);
05 });
06
07 $("#<%=chkItems.ClientID %> input:checkbox").click(function(){
if($("#<%= chkSelectAll.ClientID %>").attr('checked')
08
== true && this.checked ==false)
09 $("#<%= chkSelectAll.ClientID %>").attr('checked',false);
10 if(this.checked == true)
11 CheckSelectAll();
12 });
13
14 function CheckSelectAll()
15 {
16 var flag = true;
17 $("#<%=chkItems.ClientID %> input:checkbox").each(function() {
18 if(this.checked == false)
19 flag = false;
20 });
21 $("#<%= chkSelectAll.ClientID %>").attr('checked',flag);
22 }
23 });
24 </script>
Well above given code solves my purpose. Let’s go through the code function by function.
1 $("#<%=chkSelectAll.ClientID %>").click(function() {
$("#<%= chkItems.ClientID %>
2
input:checkbox").attr('checked',this.checked);
3 });
This code binds click event to “Select All” checkbox. It will search for all the checkbox inside the chkItems (as
checkbox list, when rendered becomes a table. See the view source.) and set the checked attribute to the value
of “Select All” checkbox. 2 Lines of code can serve your purpose. That’s why I love JQuery.
Next function binds the click event to every checkbox of checkbox list.
1 $("#<%=chkItems.ClientID %> input:checkbox").click(function(){
Inside the function, it first check for the status of “Select All”. If it’s true and the clicked checkbox is unchecked
(see Image 3), then it will uncheck the “Select All” checkbox.
if($("#<%= chkSelectAll.ClientID %>").attr('checked')
1
== true && this.checked ==false)
2 $("#<%= chkSelectAll.ClientID %>").attr('checked',false);
Next task is, if the clicked checkbox item status is checked, then we need to check the status of all the items of
checkbox list and if every item is checked, then we must check the “Select All” checkbox.
1 if(this.checked == true)
2 CheckSelectAll();
This will call a function “CheckSelectAll”. This function iterates thorugh the checkbox list and finds all the items
are checked or not. If yes, then it sets the status of “Select All” checkbox accordingly.
1 function CheckSelectAll(){
2 var flag = true;
3 $("#<%=chkItems.ClientID %> input:checkbox").each(function() {
4 if(this.checked == false)
5 flag = false;
6 });
7 $("#<%= chkSelectAll.ClientID %>").attr('checked',flag);
8}
each() method of JQuery will perfomes the iteration for specified item.

That’s it. Hope this will help you in your work.

Feel free to ask me about jQuery, I will gladly help you.

Highlight row on mouseover in


GridView using jQuery
Labels: ASP.NET, ASP.NET Grid View, GridView, jQuery, jQuery Code Examples, Jquery Code Snippets,jQuery
Codes, jQuery With ASP.NET
In my previous post, I have posted about "Formatting ASP.NET GridView using jQuery". In this post, I will
show you that how to highlight a gridview row on mouseover. See below image. (the image is not showing the
mouse cursor, but the cursor is on 3rd row.)

All we need to do is that on mouseover on gridview rows assign any CSS and on mouseout, remove that CSS.
Rather than using mouseover and mouseout method seperately, jQuery provides another method named
"hover()" which serves purpose of both the methods. Please read more here about hover().

Below jQuery code, will find all the rows of gridview and using hover method it will assign "LightGrey" color on
mouseover and then assign "White" color on mouseout.
1 $(document).ready(function() {
2 $("#<%=gdRows.ClientID%> tr").hover(function() {
3 $(this).css("background-color", "Lightgrey");
4 }, function() {
5 $(this).css("background-color", "#ffffff");
6 });
7 });
If your default backgroud color for row is other than white then put that color code instead of white. Simple and
cool... Isn't it?

But there is a problem with this code. That is it will assign the mouseover and mouseout effect on header row as
well. Try it yourself with above code. So how to resolve it? Well, we need to change above code little bit so that it
finds only those rows which are having "td", not "th". To do this, we can use "has" selector of jQuery to find out
all the rows which have td. See below jQuery code.
1 $(document).ready(function() {
2 $("#<%=gdRows.ClientID%> tr:has(td)").hover(function() {
3 $(this).css("background-color", "Lightgrey");
4 }, function() {
5 $(this).css("background-color", "#ffffff");
6 });
7 });
Hope you find this post useful.

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

Formatting ASP.NET GridView using


jQuery
Labels: ASP.NET, ASP.NET Grid View, GridView, jQuery, jQuery Code Examples, Jquery Code Snippets,jQuery
Codes, jQuery With ASP.NET
In this post, we will see how easily we can assign alternate background color of ASP.NET Grid Views rows using
jQuery. In this example, we will assign grey color to all the odd rows of GridViews. When I say Odd, that means
Rows which are having odd numbers like Row1, Row3, Row5 etc.

Let's take a ASP.NET Grid View Control and placed it on ASP.NET Page with ID "gdRows". See below.
1 <asp:GridView ID="gdRows" runat="server">
2 </asp:GridView>
jQuery provides a selector ":odd" which selects only odd elements. So we need to filter out all the odd rows and
assign the color. To filter the rows, we will use filter() method of jQuery, which takes selector as argument and
returns the elements which matches the selector. See below jQuery Code.
1 $(document).ready(function() {
$("#<%=gdRows.ClientID%> tr").filter(":odd").css("background-
2
color", "grey");
3 });
You can also use ":even" selector to assign other than default color to grid view rows.
1 $(document).ready(function() {
$("#<%=gdRows.ClientID%> tr").filter(":even").css("background-
2
color", "blue");
3 });
Feel free to contact me for any help related to jQuery, I will gladly help you.

S-ar putea să vă placă și