Documente Academic
Documente Profesional
Documente Cultură
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.
"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.
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>
1 $(document).ready(function()
2{
3 alert($("#dvExample").html());
4 });
Output:
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:
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.
<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.
Feel free to contact me for any help related to jQuery. I will gladly help you.
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.
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.
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.
Feel free to contact me for any help related to jQuery. I will gladly help you.
<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.
<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.
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 <textarea rows="20" cols="100" id="txtMultiLine">
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>
<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.
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.
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.
$(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.
#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);
}
);
});
$(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();
}
}
}
});
});
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.
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.
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:
$(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.
Feel free to contact me for any help related to jQuery, I will gladly help you.
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.
$(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/>
$(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/>
$(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.
$(document).ready(function() {
alert($("input:text").length);
});
Feel free to contact me for any help related to jQuery, I will gladly help you.
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.
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/>
$(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.
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.
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.
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>
<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.
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.
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.