Download as pdf or txt
Download as pdf or txt
You are on page 1of 21

JQUERY with asp.

net

The HTML DOM (Document Object


Model)
When a web page is loaded, the browser creates
a Document Object Model of the page.

The HTML DOM model is constructed as a tree of Objects:

The HTML DOM Tree of Objects

With the object model, JavaScript gets all the power it needs to create
dynamic HTML:

 JavaScript can change all the HTML elements in the page


 JavaScript can change all the HTML attributes in the page
 JavaScript can change all the CSS styles in the page
 JavaScript can remove existing HTML elements and attributes
 JavaScript can add new HTML elements and attributes
 JavaScript can react to all existing HTML events in the page
 JavaScript can create new HTML events in the page

What You Will Learn


In the next chapters of this tutorial you will learn:

 How to change the content of HTML elements


 How to change the style (CSS) of HTML elements
 How to react to HTML DOM events
 How to add and delete HTML elements

What is the DOM?


The DOM is a W3C (World Wide Web Consortium) standard.

The DOM defines a standard for accessing documents:

"The W3C Document Object Model (DOM) is a platform and language-


neutral interface that allows programs and scripts to dynamically
access and update the content, structure, and style of a document."

The W3C DOM standard is separated into 3 different parts:

 Core DOM - standard model for all document types


 XML DOM - standard model for XML documents
 HTML DOM - standard model for HTML documents

What is the HTML DOM?


The HTML DOM is a standard object model and programming
interface for HTML. It defines:

 The HTML elements as objects


 The properties of all HTML elements
 The methods to access all HTML elements
 The events for all HTML elements

What is JQuery?

It is a fast JavaScript Library that simplifies HTML document traversing, event


handling, animating, and Ajax interactions for rapid web development.

What you can do with JQuery?


In summary JQuery is smart javascript library which allows you to do complex
javascript code in a minute. It has also capability of performing AJAX Operations
Example 1: You can use JQuery to show tooltip on textbox focus.

Example 2: You can perform Photo Corp using JQuery


Example 3: You can fill cascading dropdown using Ajax JQuery
In Below example, When you select country, it will fill state/region drop-down and
when you select state/region, it will cities based on values in database using
JQuery Ajax web service call.

Example 4: Autocomplete JQuery Textbox.


And the example list goes on and on.

jQuery Selectors
Selectors are most useful feature in jQuery, Selectors helps to select element(s) in an
HTML document.
jQuery has large number of options for selectors, you can select an element or array of
elements by its ID, tag name, class name, with particular attributes. There are lots
options to traverse through parent and children to find out an element.
Every selector returns an array of elements rather than single element; I feel this is a very
helpful feature in jQuery while working with jQuery.
Userful Selectors Examples:
$("#selectDiv") //will return an array containing element which has id = selectDiv
$("div") //will return an array containing all "div" elements.
$(".header") //will return an array containing elements which has class name = header
$("input[name='emailaddress']") //will return an array containing "input" elements which
has name = emailaddress

Here is another different selectors .

Selector Example Selects


* $("*") All elements

#id $("#lastname") The element with id="lastname"

.class $(".intro") All elements with class="intro"

.class,.class $(".intro,.demo") All elements with the class "intro" or "demo"

element $("p") All <p> elements

el1,el2,el3 $("h1,div,p") All <h1>, <div> and <p> elements

:first $("p:first") The first <p> element

:last $("p:last") The last <p> element

:even $("tr:even") All even <tr> elements

:odd $("tr:odd") All odd <tr> elements


:first-child $("p:first-child") All <p> elements that are the first child of their
parent

:first-of-type $("p:first-of-type") All <p> elements that are the first <p> element
of their parent

:last-child $("p:last-child") All <p> elements that are the last child of their
parent

:last-of-type $("p:last-of-type") All <p> elements that are the last <p> element
of their parent

:nth-child(n) $("p:nth-child(2)") All <p> elements that are the 2nd child of their
parent

:nth-last-child(n) $("p:nth-last-child(2)") All <p> elements that are the 2nd child of their
parent, counting from the last child

:nth-of-type(n) $("p:nth-of-type(2)") All <p> elements that are the 2nd <p> element
of their parent

:nth-last-of-type(n) $("p:nth-last-of-type(2)") All <p> elements that are the 2nd <p> element
of their parent, counting from the last child

:only-child $("p:only-child") All <p> elements that are the only child of their
parent

:only-of-type $("p:only-of-type") All <p> elements that are the only child, of its
type, of their parent
parent > child $("div > p") All <p> elements that are a direct child of a
<div> element

parent descendant $("div p") All <p> elements that are descendants of a
<div> element

element + next $("div + p") The <p> element that are next to each <div>
elements

element ~ siblings $("div ~ p") All <p> elements that are siblings of a <div>
element

:eq(index) $("ul li:eq(3)") The fourth element in a list (index starts at 0)

:gt(no) $("ul li:gt(3)") List elements with an index greater than 3

:lt(no) $("ul li:lt(3)") List elements with an index less than 3

:not(selector) $("input:not(:empty)") All input elements that are not empty


:header $(":header") All header elements <h1>, <h2> ...

:animated $(":animated") All animated elements

:focus $(":focus") The element that currently has focus

:contains(text) $(":contains('Hello')") All elements which contains the text "Hello"

:has(selector) $("div:has(p)") All <div> elements that have a <p> element

:empty $(":empty") All elements that are empty

:parent $(":parent") All elements that are a parent of another


element

:hidden $("p:hidden") All hidden <p> elements

:visible $("table:visible") All visible tables

:root $(":root") The document's root element

:lang(language) $("p:lang(de)") All <p> elements with a lang attribute value


starting with "de"
[attribute] $("[href]") All elements with a href attribute

[attribute=value] $("[href='default.htm']") All elements with a href attribute value equal to


"default.htm"

[attribute!=value] $("[href!='default.htm']") All elements with a href attribute value not


equal to "default.htm"

[attribute$=value] $("[href$='.jpg']") All elements with a href attribute value ending


with ".jpg"

[attribute|=value] $("[title|='Tomorrow']") All elements with a title attribute value equal to


'Tomorrow', or starting with 'Tomorrow'
followed by a hyphen

[attribute^=value] $("[title^='Tom']") All elements with a title attribute value starting


with "Tom"

[attribute~=value] $("[title~='hello']") All elements with a title attribute value


containing the specific word "hello"

[attribute*=value] $("[title*='hello']") All elements with a title attribute value


containing the word "hello"
:input $(":input") All input elements

:text $(":text") All input elements with type="text"

:password $(":password") All input elements with type="password"

:radio $(":radio") All input elements with type="radio"

:checkbox $(":checkbox") All input elements with type="checkbox"

:submit $(":submit") All input elements with type="submit"

:reset $(":reset") All input elements with type="reset"

:button $(":button") All input elements with type="button"

:image $(":image") All input elements with type="image"

:file $(":file") All input elements with type="file"

:enabled $(":enabled") All enabled input elements

:disabled $(":disabled") All disabled input elements


:selected $(":selected") All selected input elements

:checked $(":checked") All checked input elements

using jQuery with ASP.NET

To begin with using jQuery with ASP.NET, first download the latest version the
jQuery library from jQuery website and unzip or copy the file in your project or
Visual studio solution. Microsoft Visual studio 2012 and 2015 include jQuery by
default and provide intellisense to use jQuery.

jQuery simplifies HTML document traversing, event handling, animating, and AJAX
interactions for rapid web development.The major benefits of using JQuery for latest
web applications is that it is very lightweight JavaScript library as its minified version
is just few kilobytes in size which means it loads faster on the client side

. How to use JQuery in Asp.net Web Application?


Creating your first Hello World application in JQuery

Step 1: Open Visual Studio

Step 2: Create a new web application project (Web site...)

Step 3: Open master page of your web application.


Put this line of code, above </head>
<script type="text/javascript" language="Javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>

Above line adds JQuery library reference to your web application, in simple terms
with above line you web application understands JQuery syntax and work
accordingly.

Step 4: Put following line of code in you content page inside


<asp:Content>. Below line will display "Hello World" alert when page loads.
<script language="javascript" type="text/javascript">
$(document).ready(function () {
alert("Hello World");
});
</script>
Understanding $(document).ready(function ()

If you want an JQuery event to work on your page, you should call it inside the
$(document).ready() function. Everything inside it will load as soon as the DOM is
loaded and before the page contents are loaded.

$(document) - means page on which JQuery code lies.


.ready() - means page is loaded and your JQuery code is ready to be executed.

And for that reason you may find that most of JQuery code lies within

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


$(document).ready(function () {

JQUERY CODE GOES HERE

});
</script>

So finally you will be able to display alert on page load in your asp.net web
application with JQuery.

May be this question might comes to your mind, I can show "Hello
World" alert without using JQuery then what is fun of using JQuery?
Well its too early to judge, since this article is for beginners i have explained with
simple example there is lot more coming. Please refer to my other upcoming
JQuery tutorials.

Once you have downloaded JQuery you are ready to play with it. Create a Website
project in Visual Studio and add JQuery script file in Scripts folder as shown below:
Next you need to add the JQuery script file reference in your web page. You can drag
the file from solution explorer and drop it inside the <head> tag in your page.

Once you have JQuery file reference added to the page, you can do so many magical
things on you page but for the purpose of this tutorial and to show you a simple
example I am creating two ASP.NET button controls and a Panel control on the page.
Clicking "Show Panel" button will make the panel visible with JQuery slide down
effect and clicking the "Hide Panel" button will hide the panel with JQuery slide up
effect.

<asp:Button ID="Button1" runat="server" Text="Show Panel" />


<asp:Button ID="Button2" runat="server" Text="Hide Panel" />

<br /><br />

<asp:Panel runat="server" ID="Panel1" Height="185px" Width="320px"


style="display:none;" BackColor="#FFFF99" BorderColor="Black"
BorderStyle="Solid" BorderWidth="2px">

Hello World!

</asp:Panel>
In order to tell the browser to perform some action using JQuery as soon as the
document is ready or loaded, you need to add the following script block in
the <head>section of your page. JQuery ready method specifies a function to execute
when the DOM is fully loaded and constructed by the browser and usually the best
place to attach all other event handlers and run other JQuery code.

<script type="text/javascript">

$(document).ready(function() {
// add JQuery or JavaScript code here

});

</script>
Inside the ready method handler function, first I am creating some variables to access
ASP.NET server controls by their client ids.

<script type="text/javascript">

$(document).ready(function() {

var Button1 = $("#Button1");


var Button2 = $("#Button2");
var Panel1 = $("#Panel1");

});

</script>
If you are using Master Pages and your controls are inside Content pages or inside
any other container such as Panel or Placeholder control then ASP.NET generates
client Ids which are different then their correspondent server ids. So you may not be
able to access your server side controls with the typical JQuery selector mentioned in
the above code example. In that case you can use any one of the following techniques:

$("#'<%= Button1.ClientID %>'");


or

$("[id$='_Button1']");
You can read more about these techniques at one of my HOW TOs available at "How
to Access ASP.NET Controls client id in JQuery".

Next I am binding JavaScript click event handlers with both buttons using
JQuery click method, which takes a function handler as a parameter and execute the
function every time the element click event is triggered. The complete script block
code is shown below:

<script type="text/javascript">

$(document).ready(function() {
var Button1 = $("#Button1");
var Button2 = $("#Button2");
var Panel1 = $("#Panel1");

Button1.click(function (e) {
Panel1.slideDown();
e.preventDefault();
});

Button2.click(function (e) {
Panel1.slideUp();
e.preventDefault();
});

});

</script>
Build and run your project and you will see Panel control sliding up and down with
smooth animation effect.

Assuming that you have placed the library in Script folder, add this in the head
of your ASP.NET page (simple or master). (Its a good practice to keep your all js
file under Script folder).

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

when you call this online :


<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"
type="text/javascript"></script>

In the above code, I have not used "http" protocol while referencing jQuery
from Google CDN

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

Show alert window on click of ASP.NET Button.


Assuming a ASP.NET button with ID "btnSubmit " is placed on the page.
<asp:Button ID="btnSubmit" runat="server" Text="Button" />
And now bind the click event to ASP.NET Button in document.ready section.

<script type="text/javascript">

$(document).ready(function() {

$("#btnSubmit").click(function() {

alert("Alert using jQuery");

});

});

</script>

In above jQuery code block, we have attached click event to the button using ID
selectors. Read more about other jQuery selectors and how to use them.

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

Get label value:

$('#<%=Label1.ClientID%>').text();

Set label value:

$('#<%=Label1.ClientID%>').text("New Value");

Get Textbox value:

$('#<%=TextBox1.ClientID%>').val();

Set Textbox value:

$('#<%=TextBox1.ClientID%>').val("New Value");
Get Dropdown value:

$('#<%=DropDownList1.ClientID%>').val();

Set Dropdown value:

$('#<%=DropDownList1.ClientID%>').val("New Value");

Get text of selected item in dropdown:

$('#<%=DropDownList1.ClientID%> option:selected').text();

Get Checkbox Status:

$('#<%=CheckBox1.ClientID%>').attr('checked');

Check the Checkbox:

$('#<%=CheckBox1.ClientID%>').attr('checked',true);

Uncheck the Checkbox:

$('#<%=CheckBox1.ClientID%>').attr('checked',false);

Get Radiobutton Status:

$('#<%=RadioButton1.ClientID%>').attr('checked');

Check the RadioButton:

$('#<%=RadioButton1.ClientID%>').attr('checked',true);

Uncheck the RadioButton:

$('#<%=RadioButton1.ClientID%>').attr('checked',false);

Disable any control:

$('#<%=TextBox1.ClientID%>').attr('disabled', true);

Enable any control:

$('#<%=TextBox1.ClientID%>').attr('disabled', false);
Make textbox read only:

$('#<%=TextBox1.ClientID%>').attr('readonly', 'readonly');

Selecting date example :DatePicker

he jQuery UI DatePicker is probably the most widely-used widgets, yet the most under
utilized. It comes with a huge number of configurable options and a range of utility
functions that you can use to customize the widget the way you want.
The DatePicker has an easy to use interface for selecting date. It is tied to a simple text
field which when focused on by clicking or by using tab key, presents an interactive
calendar like interface to the user, allowing a date to be selected.

Create a new file ‘datepicker.html’ in a folder. Here’s how to write the HTML code and
call the datepicker() method in the <script> tag.
<html>
<head>
<title>DatePicker Example</title>
<link href="../css/jquery-ui.css" rel="stylesheet" />
<script src="../scripts/jquery-1.11.1.min.js"></script>
<script src="../scripts/jquery-ui.min.js"></script>
<script>
$(function () {
$("#datep").datepicker();
});
</script>
</head>
<body>
<h3>Click to select a date :</h3>
<input type="text" id="datep" />
</body>
</html>
Here we are using an <input> element with id=date and binding
the datepicker() widget to this input text field. The datepicker will automatically be
positioned below the input field when a user clicks it. The calendar will be hidden when
the user clicks outside
. If the user chooses a
date, the date will then be displayed in the input field:
Live Demo: http://www.jquerycookbook.com/demos/S9-General/67-datepicker.html
jQuery UI Datepicker offer a large set of options and methods. For a full list,
see: http://api.jqueryui.com/datepicker/
Note: Do not use the HTML5 type="date" attribute in your <input> statements when
using jQuery UI DatePicker as it causes conflicts

2 - Disable the Selection of Weekends


Similar to the previous example, we can disable the weekend days using the
before ShowDay option by passing a shorthand function $.datepicker. no
Weekends that automatically disables the week end days without any other
code needed.

Create a new file ’2-datepicker.html’. Use the following code:

<script type="text/javascript>"
($ function{ )(
#"($ datepicker").datepicker{(
beforeShowDay: $.datepicker.noWeekends
;)}
;)}
/<script>
View the page in the browser and you will observe that the weekends are
disabled.
Live Demo: http://www.jquerycookbook.com/demos/S9-General/67.2-datepicker.html

More example click here


https://www.dotnetcurry.com/jquery/1209/jqueryui-datepicker-tips-tricks

You might also like