51 Recipes With Jquery and ASP - NET Controls - Preview
51 Recipes With Jquery and ASP - NET Controls - Preview
51 Recipes With Jquery and ASP - NET Controls - Preview
Recipes
with jQuery and ASP.NET
Controls
Suprotim Agarwal
Suprotim is also the founder and primary contributor to DotNetCurry, SQLServerCurry and DevCurry and
has written over 700 articles and blog posts. When he is not churning out code, he spends his time
checking out new gadgets, playing strategic video games and helps his wife (in eating) some deliciously
cooked recipes from Foodatarian
Govind Kanshi strives to create efficient solutions for his customers using his
experience and ability to dissect complex technologies available in the market.
His experience ranges from working across startup, consulting to Fortune 100
firms as well as working in product delivery. He is comfortable creating and
managing teams and is also comfortable working in individual capacity. His
interests and expertise lies across Databases, Web applications, Virtualization
and Performance tuning.
- [3]-
SAMPLE COPY - Copyright © 2009 A2Z Knowledge Visuals Pvt. Ltd.
51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls
TABLE OF CONTENTS
- [4]-
SAMPLE COPY - Copyright © 2009 A2Z Knowledge Visuals Pvt. Ltd.
51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls
- [5]-
SAMPLE COPY - Copyright © 2009 A2Z Knowledge Visuals Pvt. Ltd.
51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls
- [6]-
SAMPLE COPY - Copyright © 2009 A2Z Knowledge Visuals Pvt. Ltd.
51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls
SAMPLE CHAPTERS
Note: JavaScript should be kept in separate files. For readability, it has been included inline.
Challenge:
Users should be prevented from doing Cut, Copy and Paste operations in an ASP.NET TextBox.
Solution:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Prevent Cut, Copy and Paste Operations in a TextBox</title>
<link href="../CSS/Demos.css" rel="stylesheet" type="text/css" />
<script type='text/javascript'
src='../Scripts/jquery-1.3.2.min.js'>
</script>
<script type="text/javascript">
$(function() {
$('input[id$=tb1]').bind('cut copy paste', function(e) {
e.preventDefault();
alert('You cannot ' + e.type + ' text!');
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div class="bigDiv">
<h2>Prevent Cut, Copy and Paste Operations in a TextBox</h2>
<br /><br />
<asp:Label ID="lblEmail" runat="server"
Text="Re-Enter your Email Address"></asp:Label>
<asp:TextBox ID="tb1" runat="server"
Text="Try copying and pasting text here"
ToolTip="Try Copy/Cut/Paste in textbox"/>
<br /><br /><br />
Tip: Text can only be entered in this box. It cannot be
copied and pasted from a different textbox
</div>
</form>
</body>
</html>
- [7]-
SAMPLE COPY - Copyright © 2009 A2Z Knowledge Visuals Pvt. Ltd.
51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls
Explanation:
This recipe handles a typical requirement where you are asked to ‘confirm’ an email address and want
the user to type it manually, instead of copying and pasting it.
The jQuery bind() function binds one or more events to a handler. Observe how convenient it is to list
multiple events (cut copy paste) together and bind it to a handler.
If the user performs any of these events on the textbox, the default behavior is prevented using
e.preventDefault() and the user is alerted. The e.type describes the type of event performed.
The screenshot shown below represents how the user is informed when he/she tries to copy text from
the textbox.
Text can be edited in this textbox, but cut/copy/paste actions are prevented.
Live Demo
Browsers Supported:
- [8]-
SAMPLE COPY - Copyright © 2009 A2Z Knowledge Visuals Pvt. Ltd.
51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls
Useful Links:
http://docs.jquery.com/Events/bind
Challenge:
Users should be allowed to enter only Alphabets and Numbers in a TextBox. Non-alphanumeric
characters should be disallowed. You also want to prevent users from copying and pasting non-
alphanumeric characters into the TextBox.
Solution:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Allow Only Alphanumeric Characters in a TextBox</title>
<link href="../CSS/Demos.css" rel="stylesheet" type="text/css" />
<script type='text/javascript'
src='../Scripts/jquery-1.3.2.min.js'>
</script>
<script type="text/javascript">
$(function() {
$('input.alpha[$id=tb1]').bind('keyup blur', function() {
if (this.value.match(/[^a-zA-Z0-9 ]/g)) {
this.value = this.value.replace(/[^a-zA-Z0-9 ]/g, '');
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div class="bigDiv">
<h2>Allow Only Alphanumeric Characters in a TextBox</h2>
<asp:TextBox ID="tb1" runat="server" class="alpha"
Text="" ToolTip="Try entering Non alphanumeric char"/>
<br /><br />
Tip: Examples of some non-alphanumeric characters <br />
are ~!@~#$%^&* and so on.
</div>
</form>
</body>
</html>
- [9]-
SAMPLE COPY - Copyright © 2009 A2Z Knowledge Visuals Pvt. Ltd.
51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls
Explanation:
The code shown above matches a regular expression /[^a-zA-Z0-9 ]/g that finds all characters that are
not alphabets or numbers. If the user enters a character that is not an alphabet or number, the
character is immediately replaced with an empty string. The blur event detects characters when the
textbox looses focus whereas the keyup event detects characters after the character has been entered. I
have observed people using only the keypress event to handle this requirement, but remember that in
IE, keypress does not behave as expected for non-character keys.
As Yehuda Katz says – “My mantra has always been: keydown/keyup if you want to know the key that
was pressed; keypress if you want to know what text was detected”
If you want to accept only numbers, use /[^0-9 ]/g and for accepting only alphabets, use /[^a-zA-Z
]/g
Live Demo
Browsers Supported:
Useful Links:
http://docs.jquery.com/Events/bind
http://docs.jquery.com/Events/keyup
Challenge:
You want to restrict the user from entering more than 50 characters in an ASP.NET Multiline TextBox.
The ASP.NET Multiline TextBox ignores the MaxLength property.
Solution:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Limit Characters in a Multiline TextBox</title>
<link href="../CSS/Demos.css" rel="stylesheet" type="text/css" />
<script type='text/javascript'
src='../Scripts/jquery-1.3.2.min.js'>
- [10]-
SAMPLE COPY - Copyright © 2009 A2Z Knowledge Visuals Pvt. Ltd.
51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls
</script>
<script type="text/javascript">
$(function() {
var limit = 50;
$('textarea[id$=tb1]').keyup(function() {
var len = $(this).val().length;
if (len > limit) {
this.value = this.value.substring(0, limit);
}
$('#charLeft').text(limit - len + " characters left");
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div class="smallDiv">
<h2>Type into this textbox which accepts 50 characters overall</h2>
<asp:TextBox ID="tb1" runat="server" TextMode="MultiLine"/><br />
<span id="charLeft"></span>
</div>
</form>
</body>
</html>
Explanation:
In this example, we first capture the keyup event and calculate the number of characters in the textbox.
$('textarea[$id=tb1]').keyup(function() {
var len = $(this).val().length;
If the character exceeds the limit of the textbox (50 characters), the additional characters entered by the
user is disallowed.
Observe how we are selecting the control using textarea $('textarea[$id=tb1]'). This is because
the ASP.NET Multiline TextBox renders as a textarea.
Live Demo
- [11]-
SAMPLE COPY - Copyright © 2009 A2Z Knowledge Visuals Pvt. Ltd.
51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls
Recommended Approach
Although the solution given above restricts the user from entering more than 50 characters, this
behavior can be confusing for users who may not realize that they have reached the TextBox limit.
Instead of disallowing extra characters, a slick way of handling this requirement would be to visually
indicate to the user when the textbox limit has been exceeded. Then before submitting the form, give
the user a chance to remove the extra text. The code shown below changes the background color of the
textbox to red when the textbox limit is exceeded. The user is also prevented from submitting the form.
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Limit Characters in a Multiline TextBox</title>
<link href="../CSS/Demos.css" rel="stylesheet" type="text/css" />
<script type='text/javascript'
src='../Scripts/jquery-1.3.2.min.js'>
</script>
<script type="text/javascript">
$(function() {
var limit = 50;
var $tb = $('textarea[id$=tb1]');
$tb.keyup(function() {
var len = $(this).val().length;
if (len > limit) {
$(this).addClass('exceeded');
$('#spn').text(len - limit + " characters exceeded");
}
else {
$(this).removeClass('exceeded');
$('#spn').text(limit - len + " characters left");
}
});
$('input[id$=btnSubmit]').click(function(e) {
var len = $tb.val().length;
if (len > limit) {
e.preventDefault();
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div class="smallDiv">
<h2>Type into this textbox which accepts 50 characters overall</h2>
<asp:TextBox ID="tb1" runat="server" TextMode="MultiLine"/><br />
(This textbox accepts only 50 characters) <br />
<span id="spn"></span> <br />
- [12]-
SAMPLE COPY - Copyright © 2009 A2Z Knowledge Visuals Pvt. Ltd.
51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls
When the number of characters exceeds the textbox limit, we add the exceeded class to the textbox,
which turns the textbox background to red, indicating the user that the limit has been exceeded.
.exceeded
{
background-color:red;
}
When the user tries and submits the form now, the length of the TextBox is calculated and the user is
prevented from submitting the form, since the textbox now exceeds the permissible length.
$('input[id$=btnSubmit]').click(function(e) {
var len = $tb.val().length;
if (len > limit) {
e.preventDefault();
}
});
- [13]-
SAMPLE COPY - Copyright © 2009 A2Z Knowledge Visuals Pvt. Ltd.
51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls
When the user removes the extra text, the exceeded class is removed.
$(this).removeClass('exceeded');
Live Demo
Browsers Supported:
Useful Links:
http://docs.jquery.com/Attributes/addClass
http://docs.jquery.com/Attributes/removeClass
Challenge:
You want to check/uncheck all the checkboxes at once, in the easiest possible way.
- [14]-
SAMPLE COPY - Copyright © 2009 A2Z Knowledge Visuals Pvt. Ltd.
51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls
Solution:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Check/Uncheck All CheckBoxes At Once</title>
<link href="../CSS/Demos.css" rel="stylesheet" type="text/css" />
<script src='../Scripts/jquery-1.3.2.min.js'
type='text/javascript'>
</script>
<script type="text/javascript">
$(function() {
var $chkBox = $("input:checkbox[id$=chkAll]");
var $tblChkBox = $("table.chk input:checkbox");
$chkBox.click(function() {
$tblChkBox
.attr('checked', $chkBox
.is(':checked'));
});
</body>
</html>
Explanation:
In the Section 2 introduction, we have seen how the CheckBoxList renders as a group of input elements
of the type checkbox, inside a HTML table.
In this example, when the user clicks the checkbox (Do All), we reference all input elements of the
checkbox type inside the table, and set the ‘checked’ value of the referenced elements to true or false,
based on the checked value of the ‘Do All’ checkbox.
$chkBox.click(function() {
$tblChkBox
.attr('checked', $chkBox
.is(':checked'));
});
When the ‘Do All’ checkbox is unchecked, the CheckBoxList is unchecked too.
The code also takes into account a scenario when a user unchecks any of the individual checkboxes in
the CheckBoxList, the ‘Do All’ checkbox is also unchecked. This is achieved using the following code:
$tblChkBox.click(
function(e) {
if (!$(this)[0].checked) {
$chkBox.attr("checked", false);
}
});
- [16]-
SAMPLE COPY - Copyright © 2009 A2Z Knowledge Visuals Pvt. Ltd.
51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls
Live Demo
Browsers Supported:
Useful Links:
http://docs.jquery.com/Selectors/checked
Recipe 18: Display the Text and Value of the Selected RadioButton using
jQuery
Challenge:
Solution:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Retrieve the Text and Value of the selected RadioButton</title>
<link href="../CSS/Demos.css" rel="stylesheet" type="text/css" />
<script src='../Scripts/jquery-1.3.2.min.js'
type='text/javascript'>
</script>
<script type="text/javascript">
$(function() {
var $radBtn = $("table.tbl input:radio");
$radBtn.click(function() {
var $radChecked = $(':radio:checked');
$("#para").text('')
.append("<b>Index: </b>" +
$radChecked.val() + "<br/>")
.append("<b>Value: </b>" +
$radChecked.next().text());
});
});
</script>
</head>
- [17]-
SAMPLE COPY - Copyright © 2009 A2Z Knowledge Visuals Pvt. Ltd.
51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls
<body>
<form id="form1" runat="server">
<div class="smallDiv">
<h2>Select a RadioButton to display its Text and Value</h2><br />
The site I like the most : <br />
<asp:RadioButtonList ID="rbl" runat="server" class="tbl"
ToolTip="Select a Radio Button to see its text and value">
<asp:ListItem Text="dotnetcurry.com" Value="0"></asp:ListItem>
<asp:ListItem Text="devcurry.com" Value="1"></asp:ListItem>
<asp:ListItem Text="sqlservercurry.com" Value="2"></asp:ListItem>
</asp:RadioButtonList>
<br />
<p id="para"></p>
</div>
</form>
</body>
</html>
Explanation:
Retrieving the index and value of a radio button is a very common requirement in our applications and
can be easily achieved using jQuery. In this example, we first retrieve the radio buttons using
Since this is a RadioButtonList, the control gets rendered as a table. When the user clicks on any of the
radio buttons, we first store the checked radiobuttons in the $radChecked variable to improve selector
performance
We then use
$radChecked.next().text().
<td>
<input id="rbl_0" type="radio" name="rbl" value="0" />
<label for="rbl_0">dotnetcurry.com</label>
</td>
To access the value, which is inside the label, we use next() which finds the very next sibling of each
radiobutton, which in our case, is the label control. The value and text is displayed on the page using a
paragraph (para). The output looks similar to this:
- [18]-
SAMPLE COPY - Copyright © 2009 A2Z Knowledge Visuals Pvt. Ltd.
51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls
Live Demo
Browsers Supported:
Useful Links:
http://docs.jquery.com/Selectors/checked
- [19]-
SAMPLE COPY - Copyright © 2009 A2Z Knowledge Visuals Pvt. Ltd.