Jquery Print
Jquery Print
Jquery Print
UNIT – I
Introduction:
jQuery is a fast and concise JavaScript Library created by John Resig in 2006 with: Write less,
do more. jQuery simplifies HTML document traversing, event handling, animating, and Ajax
interactions for rapid web development.
jQuery was first released in January 2006 by John Resig at BarCamp NYC. It is currently
headed by Timmy Wilson and maintained by a team of developers. Nowadays, jQuery is widely
used technology. Most of the websites are using jQuery.
jQuery Release History:
Let's see the release dates of jQuery versions.
HTML manipulation
DOM manipulation
DOM element selection
CSS manipulation
Effects and Animations
Utilities
AJAX
HTML event methods
JSON Parsing
Extensibility through plug-ins
Why jQuery is required?
Sometimes, a question can arise that what is the need of jQuery or what difference it makes on
bringing jQuery instead of AJAX/ JavaScript? If jQuery is the replacement of AJAX and JavaScript?
For all these questions, you can state the following answers.
It is very fast and extensible.
It facilitates the users to write UI related function codes in minimum possible lines.
It improves the performance of an application.
Browser's compatible web applications can be developed.
It uses mostly new features of new browsers.
A lot of JavaScript frameworks, jQuery is the most popular and the most extendable. Many
of the biggest companies on the web design using jQuery.
Some of these companies are:
Microsoft
Google
IBM
Netflix
Local Installation
Go to the https://jquery.com/download/ to download the latest version available.
jQuery is developed by Google. To create the first jQuery example, you need to use
JavaScript file for jQuery. You can download the jQuery file from jquery.com or use the absolute
URL of jQuery file. In jQuery example, we are using the absolute URL of jQuery file. The jQuery
example is written inside the script tag.
A simple example of jQuery: File Name: firstjquery.html
<!DOCTYPE html>
<html> <head>
<title>First jQuery Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("p").css("background-color", "cyan"); });
</script> </head>
<body>
<p>The first paragraph is selected.</p> <p>The second paragraph is selected.</p>
<p>The third paragraph is selected.</p> </body> </html>
Result:
The first paragraph is selected.
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript" src = "/jquery/jquery-2.1.3.min.js">
</script>
<script type = "text/javascript">
$(document).ready(function() {
document.write("Hello, World!");
});
</script> </head>
If you want an 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. It register a ready event for the document as follows :
$(document).ready(function()
{
// do stuff when DOM is ready
});
To call any jQuery library function, use HTML script tags as shown below :
<html> <head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("div").click(function() {alert("Hello, world!");});
});
</script> </head>
<body>
<div id = "mydiv">
Click on this to see a dialogue box.
</div>
</body>
</html>
/* Filename: custom.js */
$(document).ready(function() {
$("div").click(function() {
alert("Hello, world!");
}); });
<html>
JQuery Basics:
Q). What are the basics of JQuery basics?
jQuery is a framework built-in using JavaScript capabilities(elements). So we can using all
functions and other capabilities available in JavaScript. The basic concepts are frequently used in
jQuery.
1. Numbers
2. Strings
3. Booleans
4. Objects
5. Arrays
7. Scope
8. Built-in Functions.
1. Numbers : Numbers in JavaScript are double-precision 64-bit format IEEE 754 values. They are
just as strings.
5350
120.27
0.26
2. String : A string in JavaScript is an immutable object that contains none, one or many characters.
"This is JavaScript String"
'This is JavaScript String'
4. Objects: JavaScript supports Objects concepts and to create an object using object literal are:
var emp = {
name: "Zara",
age: 10 };
5. Arrays : Array is a collection of Homogeneous data elements, which are stored in a single
memory location. An array has a length property that is useful for iteration:
var x = [];
var x = [1, 2, 3, 4, 5];
for (var i = 0; i < x.length; i++)
{
// Do something with x[i]
}
6. Functions: A function in JavaScript can be either named or anonymous. A named function can be
defined using function keyword.
function named()
{
// do some stuff here
}
A function can be defined in similar way as a normal function but it can not have any name.
A function can be assigned to a variable or passed to a method.
$(document).ready(function(){
// do some stuff here
});
The arguments object also has a callee property, which refers to the function:
function func() {
return arguments.callee;
}
func(); // ==> func
8. Context : JavaScript always refers to the current context. Within a function this context can
change, depending on the function. To specify the context for a function call using the function-
built-in methods call() and apply() methods.
$(document).ready(function() {
// this refers to window.document
});
$("div").click(function() {
// this refers to a div DOM element
});
Within the body of a function, a local variable takes precedence over a global variable with the
same name.
10. Callback : A callback is a plain JavaScript function passed to some method as an argument or
option. Some callbacks are just events, called to give the user a chance to react when a certain
state is triggered. jQuery's event system uses such callbacks everywhere:
$("body").click(function(event) {
console.log("clicked: " + event.target);
});
11. Built-in Functions: JavaScript comes along with a useful set of built-in functions. These methods
can be used to manipulate Strings, Numbers and Dates.
The Following JavaScript functions are:
charAt() : Returns the character at the specified index.
concat(): Combines the text of two strings and returns a new string.
forEach(): Calls a function for each element in the array.
indexOf(): Returns the index within the calling String object of the first occurrence of the specified value,
or -1 if not found.
pop(): Removes the last element from an array and returns that element.
push(): Adds one or more elements to the end of an array and returns the new length of the array.
reverse(): Reverses the order of the elements of an array. the first becomes the last, and the last becomes
the first.
sort():Sorts the elements of an array.
substr():Returns the characters in a string beginning at the specified location through the specified
number of characters.
toLowerCase():Returns the string value converted to lower case.
toUpperCase(): Returns the string value converted to uppercase.
toString():Returns the string representation of the number's value.
jQuery Selectors are used to select and manipulate HTML elements. They are very
important part of jQuery library. With jQuery selectors, to find or select HTML elements based on
their id, classes, attributes, types and much more from a DOM.
The selectors are used to select one or more HTML elements using jQuery and once the
element is selected then its perform various operation on that.
Note : All jQuery selectors start with a dollor sign and parenthesis e.g. $(). It is known as the
factory function.
Every jQuery selector start with this sign $(). This sign is known as the factory function. It
uses the three basic building blocks while selecting an element in a given document. So in case
using any other JavaScript library where $ sign is conflicting with some thing else then you can
replace $ sign by jQuery name and you can use function jQuery() instead of $().
How to use Selectors: The jQuery selectors can be used single or with the combination of other
selectors. They are required at every steps while using jQuery. They are used to select the exact
element in HTML document.
1. jQuery -Element Name Selector: The element selector selects all the elements that have
a tag name of T.
Syntax: $('tagname')
Parameters: Here is the description of all the parameters used by this selector .
tagname : Any standard HTML tag name like div, p, em, img, li etc.
Returns: Like any other jQuery selector, this selector also returns an array filled with the found
elements. Example:
$('p') − Selects all elements with a tag name of p in the document.
$('div') − Selects all elements with a tag name of div in the document.
Example:
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("p").css("background-color", "yellow");
});
</script> </head> <body> <div>
<p class = "myclass">This is a paragraph.</p>
<p id = "myid">This is second paragraph.</p>
<p>This is third paragraph.</p>
</div>
Result :
This is a paragraph.
2. jQuery - Element ID Selector: The element ID selector selects a single element with the
given id attribute.
Syntax: $('#elementid')
Parameters : Here is the description of all the parameters used by this selector.
Elementid: It is an element ID. If the id contains any special characters like periods(.) or colons, to
escape those characters with backslashes.
Example:
$('#myid') − Selects a single element with the given id myid.
$('div#yourid') − Selects a single division with the given id yourid.
3. jQuery - Element Class Selector: The element class selector selects all the elements
which match with the given class of the elements.
Syntax: $('.classid')
Parameters: Here is the description of all the parameters used by this selector −
classid − This is class ID available in the document.
Ex:
$('.big') − Selects all the elements with the given class ID big.
$('p.small') − Selects all the paragraphs with the given class ID small.
$('.big.small') − Selects all the elements with a class of big and small.
Result:
This is first division of the DOM.
This is second division of the DOM.
This is third division of the DOM
Selectors Examples
Selector Name Description
$('*') This selector selects all elements in the document.
$("p > *") It selects all elements that are children of a paragraph element.
$("#specialID") This selector function gets the element with id="specialID".
$(".specialClass") It gets all the elements that have the class of specialClass.
$("li:not(.myclass)") Selects all elements matched by <li>not have lass="myclass".
$("a#specialID.specialClass") It matches links with an specialID and a class of specialClass.
$("p a.specialClass") It matches links with a class of specialClass declared within <p> elements.
$("p:empty") Selects all elements matched by <p> that have no children.
$("div[p]") Selects all elements matched by <div> that contain an element matched by
<p>.
Note : We can use all the above selectors with any HTML/XML element in generic way. For example if selector $
("li:first") works for <li> element then $("p:first") it also work for <p> element.
jQuery gives to easily manipulate an element's attributes and gives access to the element so
that we can also change its properties. There are some of the attributes are used to assign the
properties.
1. Get Attribute Value
2. Set Attribute Value
3. Applying Styles.
1.Get Attribute Value: The attr() method can be used to either fetch the value of an attribute
from the first element in the set attribute values onto all matched elements.
Ex:
The Following example which fetches title attribute of <em> tag and set <div id="divid"> value
with the same value:
2. Set Attribute Value: The attr(name, value) method can be used to set the named attribute
onto all elements in the wrapped set using the passed value.
3. Applying Styles: The addClass( classes ) method can be used to apply defined style sheets
onto all the matched elements. You can specify multiple classes separated by space.
Ex: which set src attribute of an image tag to a correct location.
<html>
<head>
<title>the title</title>
<script type="text/javascript"
src="/jquery/jquery-1.3.2.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("#myimg").attr("src", "/images/jquery.jpg");
});
</script> </head>
<body>
<div>
<img id="myimg" src="/wongpath.jpg" alt="Sample image" />
</div>
</body> </html>
Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 12
Result:
Attribute Methods:
Methods Description
1. attr( properties ) Set a key/value object as properties to all matched elements.
2. attr( key, fn ) Set a single property to a value, on all matched elements.
3. removeAttr( name ) Remove an attribute from each of the matched elements.
4. hasClass( class ) Returns true if the specified class is present on at least one of the set
of matched elements.
5. removeClass( class ) Removes all or the specified class(es) from the set of matched
elements.
6. toggleClass( class ) Adds the specified class if it is not present, removes the specified class
if it is present.
7. html( ) Get the html contents (innerHTML) of the first matched element.
8. html( val ) Set the html contents of every matched element.
9. text( ) Get the combined text contents of all matched elements.
10. text( val ) Set the text contents of all matched elements.
11. val( ) Get the input value of the first matched element.
Example 1 :
<html>
<head>
<title>The Selecter Example</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("p#pid").click(function () {
$(this).toggleClass("red");
}); });
</script>
<style>
.red { color:red; }
</style> </head>
<body>
<p class="green">Click following line to see the result</p>
<p class="red" id="pid">This is first paragraph.</p>
</body> </html>
Example 2:
<html>
<head>
<title>The Selecter Example</title>
<script type="text/javascript" src="/jquery/jquery-1.3.2.min.js">
</script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
var content = $("input").val();
$("p#pid2").text(content);
});
</script>
<style>
.red { color:red; }
.green { color:green; }
</style> </head>
<body>
<input type="text" value="First Input Box"/>
<input type="text" value="Second Input Box"/>
<p class="green" id="pid1">This is <i>first paragraph</i>.</p>
<p class="red" id="pid2">This is second paragraph.</p>
</body> </html>
Result:
jQuery is a very powerful tool which provides a variety of DOM traversal methods to helps
the select elements in a document randomly as well as in sequential method. Most of the DOM
Traversal Methods do not modify the jQuery object and they are used to filter out
elements from a document based on given conditions.
Syntax:
$('selector expression').find('selector expression to find child elements');
Java Query DOM Traversing methods are to implement the concepts are:
1. Find Element by Index
2. Filtering
3. Locating Descending element. and etc…
The image below Example an HTML page as a tree (DOM tree). With jQuery traversing, you can
easily move up (ancestors), down (descendants) and sideways (siblings) in the tree, starting from
Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 14
the selected (current) element. This movement is called traversing - or moving through - the DOM
tree.
The jQuery library includes various methods to traverse DOM elements in a DOM
hierarchy. The following jQuery methods for traversing DOM elements are:
Methods Description
children() To get all the child elements of the specified elements.
parent() Get the parent of the specified element(s).
each() Iterate over specified elements and execute specified call back
function for each element.
find() Get all the specified child elements of each specified element(s).
first() Get the first occurrence of the specified element
next() Get the immediately following sibling of the specified element.
prev() Get the immediately preceding sibling of the specified element.
siblings() Get the siblings of each specified element(s)
offsetParent() Returns a jQuery collection with the positioned parent of the first
matched element.
1. Find Elements by Index:
Every list has its own index, and can be located directly by using eq(index) Method.
Every child element starts its index from zero, thus, list item 2 would be accessed by using $
("li").eq(1) and so on.
<html>
<head>
<title>the title</title>
</head> <body> <div> <ul>
<li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
<li>list item 6</li>
</ul> </div> </body> </html>
Result:
list item 1
list item 2
list item 3
list item 4
list item 5
list item 6
Example 1:
<html>
<head>
<title>the title</title>
<script type="text/javascript"
src="/jquery/jquery-1.3.2.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("li").eq(2).css({"color":"red",
"background-color":"green"});
}); </script> </head>
<body>
<div> <ul>
<li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
<li>list item 6</li>
</ul> </div> </body> </html>
Result:
list item 1
list item 2
list item 3
list item 4
3. Setting Element Width & Height:
The width( val ) and height( val ) method can be used to set the width and height
respectively of any element. Following simple example which sets the width of first division
element whereas rest of the elements have width set by style sheet:
Example:
<html>
<head>
<title>the title</title>
<script type="text/javascript"
src="/jquery/jquery-1.3.2.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("div:first").width(100);
$("div:first").css("background-color", "blue");
}); </script>
<style>
div{ width:70px; height:50px; float:left; margin:5px;
background:red; cursor:pointer; }
</style> </head>
<body>
<div></div>
<div>d</div>
<div>d</div>
<div>d</div>
<div>d</div> </body>
</html>
d d d
Elements provide a range of DOM- methods to find elements, and extract and manipulate
their data. The DOM getters are contextual: called on a parent Document they find matching
elements under the document; called on a child element they find elements under that child.
Element data:
attr(String key) to get and attr(String key, String value) to set attributes
attributes() to get all attributes
id(), className() and classNames()
text() to get and text(String value) to set the text content
html() to get and html(String value) to set the inner HTML content
outerHtml() to get the outer HTML value
data() to get data content (e.g. of script and style tags)
tag() and tagName()
1. Content Manipulation: The html( ) method gets the html contents (inner HTML) of the
first matched element.
Syntax: selector.html( )
Example: The Following example which makes use of .html() and .text(val) methods. Here .html()
retrieves HTML content from the object and then .text( val ) method sets value of the object using
passed parameter:
<html>
<head>
<title>the title</title>
<script type="text/javascript"
src="/jquery/jquery-1.3.2.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("div").click(function () {
var content = $(this).html();
$("#result").text( content );
}); });
</script>
<style>
#division{ margin:10px;padding:12px;
border:2px solid #666;
width:60px;
} </style> </head>
Example: <html>
<head>
<title>the title</title>
<script type="text/javascript"
src="/jquery/jquery-1.3.2.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("div").click(function () {
var content = 'div class="div"';
$("#destination").wrap(document.createElement(content));
}); });
</script>
<style>
.div{ margin:10px;padding:12px;
border:2px solid #666;
width:60px;
}
</style> </head>
<body>
<p>Click on any square below to see the result:</p>
<div class="div" id="destination">THIS IS TEST</div>
<div class="div" style="background-color:blue;">ONE</div>
<div class="div" style="background-color:green;">TWO</div>
<div class="div" style="background-color:red;">THREE</div>
</body> </html>
TWO
THREE
The ability to create dynamic web pages by using events. Events are actions that can be
defined in the Web Applications. An event represents the precise moment when something
happens.
A binding event
Example : <html>
<head>
<title>The jQuery Example</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('div').bind('click', function( event ){
alert('Hi there!');
}); });
</script> <style>
.div{ margin:10px;padding:12px; border:2px solid #666; width:60px;}
</style> </head>
<body>
<p>Click on any square below to see the result:</p>
<div class="div" style="background-color:blue;">ONE</div>
<div class="div" style="background-color:green;">TWO</div>
<div class="div" style="background-color:red;">THREE</div>
</body> </html>
Result: This code will cause the division element to respond to the click event; when a user clicks
inside this division thereafter, the alert will be shown.
ONE
TWO
THREE
Example:
<html>
<head>
<title>the title</title>
<script type="text/javascript"
src="/jquery/jquery-1.3.2.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
function aClick() {
$("div").show().fadeOut("slow");
}
$("#bind").click(function () {
$("#theone").click(aClick)
.text("Can Click!");
});
$("#unbind").click(function () {
$("#theone").unbind('click', aClick)
.text("Does nothing...");
JQuery Effects:
Q). Explain about JQuery Effects with examples?
jQuery provides a simple interface for doing different kind of amazing effects. jQuery
methods allow us to quickly apply commonly used effects with a minimum configuration.
To create dynamic web pages by using events. Events are actions that can be detected in
Web Application. The Following examples events are:
A mouse click
A web page loading
Taking mouse over an element
Submitting an HTML form
A keystroke on your keyboard, etc.
When these events are triggered, then use a custom function to do whatever you want with the
event. These custom functions call Event Handlers and to covers all the important jQuery
methods to create visual effects.
jQuery enables to add effects on a web page. Jquery effects are used to perform the special events
are :
Showing
Hiding
Fading
Sliding
animation effects.
Syntax for show() method :
[selector].show( speed, [callback] );
JQuery effect methods are used to create events by using speed and callback parameters. The
description of all the parameters:
speed − A string representing one of the three predefined speeds ("slow", "normal", or
"fast") or the number of milliseconds to run the animation (e.g. 1000).
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("#show").click(function () {
$(".mydiv").show( 1000 );
});
$("#hide").click(function () {
$(".mydiv").hide( 1000 );
}); });
</script>
<style>
.mydiv{
margin:10px;
padding:12px;
border:2px solid #666;
width:100px;
height:100px;
}
</style> </head>
<body>
<div class = "mydiv">
This is a SQUARE
</div>
<input id = "hide" type = "button" value = "Hide" />
<input id = "show" type = "button" value = "Show" />
</body>
</html>
SHOW HIDE
Example:
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$(".clickme").click(function(event){
$(".target").toggle('slow', function(){
$(".log").text('Transition Complete');
});
});
});
</script>
<style>
.clickme{
margin:10px;
padding:12px;
border:2px solid #666;
width:100px;
height:50px;
}
</style> </head>
<body>
<div class = "content">
<div class = "clickme">Click Me</div>
<div class = "target">
<img src = "./images/jquery.jpg" alt = "jQuery" />
</div>
<div class = "log"></div>
</div>
</body>
</html>
Result:
Click Here
SHOW HIDE
JQuery Fade:
Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 32
Q). What is a Jquery Fade? And Explain?
The jQuery fadeIn() method is used to fade in a hidden element. The optional callback
parameter is a function to be executed after the fading completes. Like other jQuery effects
methods, optionally specify the duration or speed parameter for
the slideUp() and slideDown() methods to control, how long the slide animation will run(executed).
Durations can be specified either using one of the predefined string 'slow' or 'fast', or in a number
of milliseconds; higher values indicate slower animations.
jQuery Fading Methods: With jQuery can be fade an element in and out of visibility. jQuery has the
following fade methods:
1. fadeIn()
2. fadeOut()
3. fadeToggle()
4. fadeTo()
Syntax: $(selector).fadeIn(speed,callback);
The optional speed parameter specifies the duration of the effect. It can take the following
values: "slow", "fast", or milliseconds.
The optional callback parameter is a function to be executed after the fading completes.
Example: $("button").click(function(){
$("#div1").fadeIn(); $("#div2").fadeIn("slow"); $
("#div3").fadeIn(3000); });
2. FadeOut(): The jQuery fadeOut() method is used to fade out a visible element.
Syntax: $(selector).fadeOut(speed,callback);
The optional speed parameter specifies the duration of the effect. It can take the following values:
"slow", "fast", or milliseconds.
The optional callback parameter is a function to be executed after the fading completes.
Example: $("button").click(function(){
$("#div1").fadeOut();
$("#div2").fadeOut("slow"); $("#div3").fadeOut(3000); });
3. FadeToggel(): The jQuery fadeToggle() method toggles between the fadeIn() and fadeOut()
methods.
If the elements are faded out, fadeToggle() will fade them in.
If the elements are faded in, fadeToggle() will fade them out.
Syntax:
$(selector).fadeToggle(speed,callback);
The optional speed parameter specifies the duration of the effect. It can take the following values:
"slow", "fast", or milliseconds.
The optional callback parameter is a function to be executed after the fading completes.
Example: $("button").click(function(){
$("#div1").fadeToggle(); $("#div2").fadeToggle("slow");
$("#div3").fadeToggle(3000); });
Syntax: $(selector).fadeTo(speed,opacity,callback);
The required speed parameter specifies the duration of the effect. It can take the following values:
"slow", "fast", or milliseconds. The required opacity parameter in the fadeTo() method specifies
fading to a given opacity (value between 0 and 1).
The optional callback parameter is a function to be executed after the function completes.
Example : $("button").click(function(){
$("#div1").fadeTo("slow", 0.15);
$("#div2").fadeTo("slow", 0.4);
$("#div3").fadeTo("slow", 0.7);
});
JqueryUI is the most popular front end frameworks currently. It is sleek, intuitive, and
powerful mobile first front-end framework for faster and easier web development. It uses HTML,
CSS and Javascript. which we can use to create complex web applications GUI with ease. It is
divided into sections such as JqueryUI Basic Structure, JqueryUI CSS, JqueryUI Layout
Components and JqueryUI Plugins. Each of these sections contain related topics with simple and
useful examples.
jQueryUI stands for jQuery User Interface. It is a collection of animated visual effects, GUI
widgets, and themes implemented with jQuery, CSS, HTML and JavaScript. These new plug-ins add
a lot of new functionalities in the jQuery core library.
It is a very popular and powerful mobile first front-end framework used for faster and
easier web development. According to a survey it is used on over 176000 websites, making it the
second most popular JavaScript library on the Web.
jQuery UI History: jQueryUI is a free and open source software first published and released in
September 2007. It is distributed by jQuery foundation under the MIT license.
jQuery UI stands for jQuery User Interface. It is a collection of animated visual effects, GUI
widgets, and themes implemented with jQuery, CSS, HTML and JavaScript. These new plug-ins add
a lot of new functionalities in the jQuery core library. It is a very popular and powerful mobile first
front-end framework used for faster and easier web development. Jquery UI is categorized into four groups
are :
1. Interactions
2. Widgets
3. Effects
4. Utilities.
Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 35
The structure of the library is as shown in the image below :
Interactions − Interactions are the set of plug-ins which facilitates interactive plugins like
drag, drop, resize and more which give the user to interact with DOM elements.
Draggable
Droppable
Resizable
Selectable
Sortable
Widgets − Widgets are the jQuery plug-ins which makes you able to create user interface
elements like accordian, date picker etc.
Accordion
Autocomplete
Dialog
Button
Date Picker
Menu
Progress Bar
Tabs
Tooltip
Slider
Spinner
Effects The internal jQuery effects contain a full suite of custom animation and transition
for DOM elements.
Hide
Show
Add Class
Remove Class
Switch Class
Toggle Class
Color Animation
Effect
Toggle
Utilities − These are a set of modular tools the JqueryUI library uses internally.
Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 36
Position: It is used to set the position of the element according to the other
element's alignment (position).
Benefits of JqueryUI : The below are some of the benefits of Jquery UI:
<!DOCTYPE html>
<html>
<head>
<link href = https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
</head>
<body>
<div id = "div6" style = "border:solid 1px;background:#eee; height:50px;">
<span>You can duplicate me....</span>
</div>
<script>
$("#div6 span").draggable ({
helper : "clone"
});
</script> </body> </html>
Syntax :
1. $(selector, context).droppable (options);
2. $(selector, context).droppable({option1: value1, option2: value2..... });
Example:
3. Resizeble: jQueryUI provides resizable() method to resize any DOM element. This method
simplifies the resizing of element which otherwise takes time and lot of coding in HTML. The
resizable () method displays an icon in the bottom right of the item to resize.
$ (selector, context).resizable (options) Method
The resizable (options) method declares that an HTML element can be resized.
The options parameter is an object that specifies the behavior of the elements involved when
resizing.
Syntax:
1. $(selector, context).resizable (options);
animate :This option when set to true is used to enable a visual effect during
2
resizing when the mouse button is released. The default value is false (no effect).
animateDuration: This option is used to set the duration (in milliseconds) of the
3 resizing effect. This option is used only when animate option is true. By default its
value is "slow".
aspectRatio:This option is used to indicate whether to keep the aspect (height and
5
width) ratio for the item. By default its value is false.
autoHide: This option is used to hide the magnification icon or handles, except
6
when the mouse is over the item. By default its value is false.
cancel: This option is used to prevent resizing on specified elements. By default its
7
value is input, text area, button, select, option.
disabled: This option disables the resizing mechanism when set to true. The mouse
10 no longer resizes elements, until the mechanism is enabled, using the resizable
("enable"). By default its value is false.
distance: With this option, the resizing starts only when the mouse moves a
11 distance(pixels). By default its value is 1 pixel. This can help prevent unintended
resizing when clicking on an element.
ghost: This option when set to true, a semi-transparent helper element is shown
12 for resizing. This ghost item will be deleted when the mouse is released. By default
its value is false.
grid: This option is of type Array [x, y], indicating the number of pixels that the
13 element expands horizontally and vertically during movement of the mouse. By
default its value is false.
maxHeight:This option is used to set the maximum height the resizable should be
15
allowed to resize to. By default its value is null.
maxWidth: This option is used to set the maximum width the resizable should be
16
allowed to resize to. By default its value is null.
minHeight: This option is used to set the minimum height the resizable should be
17
allowed to resize to. By default its value is 10.
minWidth: This option is used to set the minimum width the resizable should be
18
allowed to resize to. By default its value is 10.
Syntax:
1. $(selector, context).selectable (options);
appendTo:This option is tells which element the selection helper (the lasso) should
1
be appended to. By default its value is body.
autoRefresh: if set to true, the position and size of each selectable item is computed
2
at the beginning of a select operation. By default its value is true.
delay: This option is used to set time in milliseconds and defines when the selecting
4
should start. This can be used to prevent unwanted selections. By default its value is 0.
5 disabled: when set to true, disables the selection mechanism. Users cannot select the
elements until the mechanism is restored using the selectable ("enable") instruction.
distance: the distance (in pixels) the mouse must move to consider the selection in
6 progress. This is useful, for example, to prevent simple clicks from being interpreted
as a group selection. By default its value is 0.
filter: selector indicating which elements can be part of the selection. By default its
7
value is *.
tolerance: specifies which mode to use for testing whether the selection helper (the
8
lasso) should select an item. By default its value is touch.
Syntax:
$(selector, context).sortable(options);
appendTo: This option specifies the element in which the new element created
1 with options.helper will be inserted during the time of the move/drag. By default its
value is parent.
axis: This option indicates an axis of movement ("x" is horizontal, "y" is vertical). By
2
default its value is false.
cancel: This option is used to prevent sorting of elements by clicking on any of the
3
selector elements. By default its value is "input,textarea,button,select,option".
connectWith: This option is a Selector that identifies another sortable element that
4
can accept items from this sortable. By default its value is false.
containment: This option indicates an element within which the displacement takes
place. The element will be represented by a selector (only the first item in the list will
5
be considered), a DOM element, or the string "parent" (parent element) or "window"
(HTML page).
6 cursor: Specifies the cursor CSS property when the element moves. It represents the
cursorAt: Sets the offset of the dragging helper relative to the mouse cursor.
7 Coordinates can be given as a hash using a combination of one or two keys: { top, left,
right, bottom }. By default its value is "false".
delay: Delay, in milliseconds, after which the first movement of the mouse is taken
8
into account. The displacement may begin after that time. By default its value is "0".
disabled: This option if set to true, disables the sortable functionality. By default its
9
value is false.
distance: Number of pixels that the mouse must be moved before the sorting starts. If
10 specified, sorting will not start until after mouse is dragged beyond distance. By
default its value is "1".
dropOnEmpty:This option if set to false, then items from this sortable can't be
11
dropped on an empty connect sortable. By default its value is true.
scrollSpeed: This option indicates the scrolling speed of the display once the scrolling
12 begins. By default its value is 20.
zIndex: This option represents z-index for element/helper while being sorted. By
13
default its value is 1000.
The accordion (options) method declares that an HTML element and its contents should be
treated and managed as accordion menus. The options parameter is an object that specifies the
appearance and behavior of the menu involved.
active :Indicates the index of the menu that is open when the page is first accessed. By
1
default its value is 0, i.e the first menu.
animate: This option is used to set how to animate changing panels. By default its
2
value is {}.
collapsible: This option when set to true, it allows users to close a menu by clicking
3 on it. By default, clicks on the open panel’s header have no effect. By default its value
is false.
disabled: This option when set to true disables the accordion. By default its value
4
is false.
event: This option specifies the event used to select an accordion header. By default
5
its value is click.
JQueryUI provides an autocomplete widget — a control that acts a lot like a <select>
dropdown, but filters the choices to present only those that match what the user is typing into a
control. jQueryUI provides the autocomplete()method to create a list of suggestions below the
input field and adds new CSS classes to the elements concerned to give the appropriate style.
Any field that can receive input can be converted into an Autocomplete,
namely, <input> elements, <textarea> elements, and elements with the contenteditableattribute.
Syntax: $(selector, context).autocomplete (options);
1. $(selector, context).autocomplete ("action", params) ;
The following table lists the different options that can be used with this method :
1 appendTo: This option is used append an element to the menu. By default its value
autoFocus: This option when set to true, the first item of the menu will automatically
2
be focused when the menu is shown. By default its value is false.
minLength: The number of characters that must be entered before trying to obtain
3 the matching values (as specified by the source option). This can prevent too large a
value set from being presented.
3. Buttons: jQueryUI provides button() method to transform the HTML elements (like buttons,
inputs and anchors) into themeable buttons, with automatic management of mouse movements
on them, all managed transparently by jQuery UI.
Syntax:
1. $(selector, context).button (options);
The following table lists the different options that can be used with this method :
disabled: This option deactivates the button is set to true. By default its value
1
is false.
icons: y7This option specifies that one or two icons are to be displayed in the button:
2 primary icons to the left, secondary icons to the right. By default its value is primary:
null, secondary: null.
label: This option specifies text to display on the button that overrides the natural
3 label. If omitted, the natural label for the element is displayed. By default its value
is null.
text: This option specifies whether text is to be displayed on the button. If specified
4 as false, text is suppressed if (and only if) the icons option specifies at least one icon.
By default its value is true.
4. Dialog: Dialog boxes are one of the nice ways of presenting information on an HTML page. A
dialog box is a floating window with a title and content area. This window can be moved, resized,
and of course, closed using "X" icon by default.
Syntax:
1. $(selector, context).dialog (options);
2. $(selector, context).dialog ("action", [params]);
The following table lists the different options that can be used with this method:
resizable: This option unless set to false, the dialog box is resizable in all directions. By
1
default its value is true.
show: This option is an effect to be used when the dialog box is being opened. By default
2
its value is null.
title: This option specifies the text to appear in the title bar of the dialog box. By default
3
its value is null.
width: This option specifies the width of the dialog box in pixels. By default its value
4
is 300.
5. DatePickers: Datepickers in jQueryUI allow users to enter dates easily and visually. We can
customize the date format and language, restrict the selectable date ranges and add in buttons
and other navigation options easily.
The following table lists the different options that can be used with this method −
1 altFormat: This option is used when an altField option is specified. It provides the format
appendText: This option is a String value to be placed after the <input> element,
2
intended to show instructions to the user. By default its value is "".
autoSize: This option when set to true resizes the <input> element to accommodate the
3
datepicker’s date format as set with the dateFormat option. By default its value is false.
beforeShow: This option is a callback function that’s invoked just before a datepicker is
4 displayed, with the <input> element and datepicker instance passed as parameters. By
default its value is "".
beforeShowDay: This option is a callback function which takes a date as parameter, that’s
5 invoked for each day in the datepicker just before it’s displayed, with the date passed as
the only parameter. By default its value is null.
calculateWeek: This option is a custom function to calculate and return the week number
6 for a date passed as the lone parameter. The default implementation is that provided by
the $.datepicker.iso8601Week()utility function.
changeMonth: This option if set to true, a month dropdown is displayed, allowing the
7 user to directly change the month without using the arrow buttons to step through them.
By default its value is false.
changeYear: This option if set to true, a year dropdown is displayed, allowing the user to
directly change the year without using the arrow buttons to step through them.
8
Option yearRange can be used to control which years are made available for selection. By
default its value is false.
closeText: This option specifies the text to replace the default caption of Done for the
9 close button. It is used when the button panel is displayed via
the showButtonPanel option. By default its value is "Done".
6. Menu: The jQuery UI Menu widget consists of a main menu bar with pop up menus. Some
items in the pop up menus also have sub pop up menus. These menus are created by using
markup elements as long as the parent child relationship is maintained. The jQuery UI uses the
menu() method to create menus.
Syntax: 1. $(selector, context).menu (options);
2. $(selector, context).menu({option1: value1, option2: value2..... });
Following is a list of different options that can be used with this method.
Option Description
disable If set option to true, it disables the menu. By default its value is false.
d
menus This option is a selector for the elements that serve as the menu container, including
sub-menus. By default its value is ul.
positio sets the position of submenus in relation to the associated parent menu item. By
n default its value is { my: "left top", at: "right top" }.
role This option is used to customize the aria roles used for the menu and menu items. By
default its value is menu.
7. Progress bar: Progress bars indicate the completion percentage of an operation or process. We
can categorize progress bar as determinate progress bar and indeterminate progress bar.
Determinate progress bar should only be used in situations where the system can accurately update
the current status. A determinate progress bar should never fill from left to right, then loop back to
empty for a single process.
If the actual status cannot be calculated, an indeterminate progress bar should be used to provide
user feedback.
jQueryUI provides an easy-to-use progress bar widget that we can use to let users know that our
application is hard at work performing the requested operation. jQueryUI provides progressbar()
method to create progress bars. Syntax:
The following table lists the different options that can be used with this method :
disabled
when set to true disables the progress bars. By default its value is false.
max To sets the maximum value for a progress bar. By default its value is 100.
value :Tospecifies the initial value of the progress bar. By default its value is 0.
8. Spinner: widget adds a up/down arrow to the left of a input box thus allowing a user to
increment/decrement a value in the input box. It allows users to type a value directly, or modify
an existing value by spinning with the keyboard, mouse or scrollwheel. It also has a step feature to
skip values. In addition to the basic numeric features, it also enables globalized formatting options
(ie currency, thousand separator, decimals, etc.) thus providing a convenient internationalized
masked entry box. jQueryUI provides spinner() method which creates a spinner.
Example: 1
<!doctype html>
1. <html lang="en">
2. <head>
3. <meta charset="utf-8">
4. <title>jQuery UI ProgressBar functionality</title>
5. <link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet">
6. <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
7. <script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
8. <style>
9. .ui-widget-header { background: blue;
10. border: 1px solid #DDDDDD;
11. color: #333333;
12. font-weight: bold;
13. } </style> <script>
14. $(function() {
15. $( "#progressbar-1" ).progressbar({ value: 30
16. }); });
17. </script> </head>
18. <body> <div id="progressbar-1"></div>
19. </body> </html>
Q). Explain about Jquery UI Effects methods with examples?
Effects The internal jQuery effects contain a full suite of custom animation and transition for DOM
elements.
1. Hide
2. Show
3. Add Class
4. Remove Class
5. Switch Class
6. Toggle Class
7. Color Animation
8. Effect
9. Toggle
1. Hide: the hide() method, which is one of the methods used to manage jQueryUI visual effects.
effect() method applies an animation effect to hide elements.
Options: This is of type Object and indicates effect-specific settings and easing. Additionally, each
2 effect has its own set of options that can be specified common across multiple effects described in
the table jQueryUI Effects.
Duration : This is of type Number or String, and indicates the number of milliseconds of the effect.
3
Its default value is 400.
Complete: This is a callback method called for each element when the effect is complete for this
4
element.
jQueryUI Effects: The following table describes the various effects that can be used with the hide()
method :
Sr.No
Effect & Description
.
1 Blind: Shows or hides the element in the manner of a window blind: by moving the bottom edge down
or up, or the right edge to the right or left, depending upon the specified direction and mode.
Bounce: Causes the element to appear to bounce in the vertical or horizontal direction, optionally
2
showing or hiding the element.
Clip: Shows or hides the element by moving opposite borders of the element together until they meet in
3
the middle, or vice versa.
4 Drop: Shows or hides the element by making it appear to drop onto, or drop off of, the page.
Explode: Shows or hides the element by splitting it into multiple pieces that move in radial directions as
5
if imploding into, or exploding from, the page.
Fade: Shows or hides the element by adjusting its opacity. This is the same as the core fade effects, but
6
without options.
Fold:Shows or hides the element by adjusting opposite borders in or out, and then doing the same for
7
the other set of borders.
Highlight:Calls attention to the element by momentarily changing its background color while showing
8
or hiding the element.
10 Pulsate:Adjusts the opacity of the element on and off before ensuring that the element is shown or
Size:Resizes the element to a specified width and height. Similar to scale except for how the target size is
14
specified.
15 Slide:Moves the element such that it appears to slide onto or off of the page.
Transfer:Animates a transient outline element that makes the element appear to transfer to another
16 element. The appearance of the outline element must be defined via CSS rules for the ui-effects-transfer
class, or the class specified as an option.
2. Show: This chapter will discuss the show() method, which is one of the methods used to
manage jQueryUI visual effects. show() method displays an item using the indicated effect.
show() method toggles the visibility of the wrapped elements using the specified effect.
Syntax:
3. Add Class: the addClass() method, which is one of the methods used to manage jQueryUI
visual effects. addClass() method allow animating the changes to the CSS properties.
addClass() method add specified classes to the matched elements while animating all style
changes.
removeClass() method removes the specified classes to the matched elements while animating all
style changes.
{ backgroundColor: "black",
color: "white"
} );
6. Effect: the effect() method, which is one of the methods used to manage jQueryUI visual
effects. effect() method applies an animation effect to the elements without having to show or hide
it.
<!doctype html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>jQuery UI Toggle Example</title>
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<!-- CSS -->
<style>
.toggler { width: 500px; height: 200px; }
#button { padding: .5em 1em; text-decoration: none; }
#effect { width: 240px; height: 135px; padding: 0.4em; position: relative; }
#effect h3 { margin: 0; padding: 0.4em; text-align: center; }
</style>
<script>
$(function() {
function runEffect() {
$( "#effect" ).toggle('explode', 300);
};
$( "#button" ).click(function() {
runEffect();
return false;
});
Toggle
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt
ut labore.
Toggle
Jquery UI Themes
Introduction:
Themes are not a new concept. probably rolled out a using Cascading Style Sheet (CSS)
styles and classes to format the look and feel of a good websites. Using a framework standardizes
the approach and lessens the amount of work and code needing to be written.
jQuery UI is now the industry standard for theme implementation. There are other choices,
such as Dojo (coupled with Dijit) or Ext JS, but jQuery UI combines themes with the use of widgets,
which are the elements with which users interact date pickers or buttons. When dissecting the
inner workings of the files that make up a jQuery UI theme, what you find is nothing more than
CSS and JavaScript. But it's the thought process and standardization that have gone into this use of
CSS and JavaScript that makes jQuery UI such an excellent platform for building the look and feel
of a website.
Q). Explain about Jquery UI Themes with examples?
jQuery UI combines themes with the use of widgets, which are the elements with which
users interact date pickers or buttons. When dissecting the inner workings of the files that make
up a jQuery UI theme.
The jQuery UI platform consists of two sub-frameworks:
1. a widget framework: which contains the Widget Factory and a set of commonly used widgets,
2. CSS framework. The Widget Factory provides the basis for all jQuery UI widgets, including those
common widgets included in the set of widgets.
Customise UI widgets:
The three widgets in this application are defined using <div> statements for the most part
(except for the button, which already has a tag in HTML). These widgets are defined in the
following code:
Widget events:
The widgets are fundamentally JavaScript objects, they can be set up with events that fire during
the lifetime of the website application. events fire, they are caught by either your website's
provided JavaScript code or handled within the widgets.
1 $( "#dlg_popup" ).dialog({
2 drag: function(event, ui) { ... }
3 });
Widget methods:
Methods are associated with the widget and allow the execution of pre-written functionality on a
particular widget to have it perform a specific action. an example of calling a widget's method:
1 $(“#dlg_popup”).dialog("moveToTop”);
Switching themes: Code can be included in HTML and JavaScript files that give the ability to
switch themes on the fly using a drop-down menu. the changes to the HTML source code to
make such a change.
Using the ThemeRoller changes can be made to an existing jQuery theme (as a starting
point) to create a unique theme. Doing so eliminates the need to create the theme from scratch. It
also means expertise in CSS isn't required, and the tool allows you to view changes to existing
themes and widgets on the fly.
Font Settings - Allows general changes to the font used throughout a theme.
Corner Radius - Controls the rounding (or lack) of corners for various widgets.
Header/Toolbar - Provides the look and feel for headers used in the various widgets.
Content - Provides settings to control the main body of the widgets.
Clickable - Controls various states that the widgets use.
Example:
A jQuery plugin is simply a new method that we use to extend jQuery's prototype object. By
extending the prototype object, it can be enable all jQuery objects to inherit any methods that you
add. whenever you call jQuery()to creating a new jQuery object, with all of jQuery's methods
inherited.
The idea of a plugin is to do something with a collection of elements. It consider each method that
comes with the jQuery core a plugins such as:
1. .fadeOut()
2. .addClass().
It can make own plugins and use them privately in a code or release them into the wild. There are
thousands of jQuery plugins available online.
jQuery plugin makes simple clientside form validation easy to customization options. It
makes a good choice if you’re building something new from scratch. The plugin comes bundled
with a useful set of validation methods, including URL and email validation, while providing an API
to write own methods. All bundled methods come with default error messages in english and
translations into 37 other languages.
The quality of jQuery plugins varies widely. Many plugins are extensively tested and well-
maintained. Some plugins, mainly jQuery UI, are maintained by the jQuery team. The quality of
these plugins is as good as jQuery itself.
Example: <html>
<head>
<title>the title</title>
<script type="text/javascript"
src="/jquery/jquery-1.3.2.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("#driver").click(function(event){
$('#stage').load('/jquery/result.html');
}); });
</script>
</head>
<body>
<p>Click on the button to load result.html file:</p>
<div id="stage" style="background-color:blue;">
STAGE
</div> <input type="button" id="driver" value="Load Data" />
</body> </html>
Here load() initiates an Ajax request to the specified URL /jquery/result.html file. After loading
this file, all the content would be populated inside <div> tagged with ID stage. Assuming, our
/jquery/result.html file has just one HTML line:
Passing Data to the Server: Many times it collect input from the user and to pass that input to the
server for further processing. JQuery AJAX made it easy enough to pass collected data to the server
using data parameter of any available Ajax method.
Advantages to Ajax:
Ajax should be used anywhere in a web application where small amounts of information
could be saved or retrieved from the server without posting back the entire pages.
A good example of this is data validation on save actions. Another example would be to change the
values in a drop down list-box based on other inputs, such as state and college list boxes. When the
user selects a state, the college list box will repopulate with only colleges and universities in that
state. Other features include text hints and autocomplete text boxes. The client types in a couple of
letters and a list of all values that start with those letters appear below.
A callback is made to a web service that will retrieve all values that begin with these characters.
This is a fantastic feature that would be impossible without Ajax and is also part of the Ajax
Control Toolkit.
Segue recently used Ajax to support a client application that had problems due to limited
bandwidth and page size. The combination caused the application to take too long to retrieve data
and display it on the page. Sometimes, the web server would simply not have the resources to
handle the request and timeout. The best solution for this issue was Ajax.
JSON or JavaScript Object Notation is a lightweight text-based open standard designed for
human-readable data interchange. Conventions used by JSON are known to programmers, which
include C, C++, Java, Python, Perl, etc.
JSON stands for JavaScript Object Notation.
The format was specified by Douglas Crockford.
It was designed for human-readable data interchange.
It has been extended from the JavaScript scripting language.
The filename extension is .json.
JSON Internet Media type is application/json.
The Uniform Type Identifier is public.json.
Characteristics of JSON
There would be a situation when server would return JSON string against your request.
JQuery utility function getJSON() parses the returned JSON string and makes the resulting string
available to the callback function as first parameter to take further action.
Syntax : [selector].getJSON( URL, [data], [callback] );
the description of all the parameters:
URL: The URL of the server-side resource contacted via the GET method.
Data: An object whose properties serve as the name/value pairs used to construct a query string
to be appended to the URL, or a preformatted and encoded query string.
Callback: A function invoked when the request completes. The data value resulting from digesting
the response body as a JSON string is passed as the first parameter to this callback, and the status
as the second.
Many developers use JSON to pass AJAX updates between the client and the server.
Websites updating live sports scores can be considered as an example of AJAX. If these scores
have to be updated on the website, then they must be stored on the server so that the webpage
can retrieve the score when it is required. This is where we can make use of JSON formatted data.
Any data that is updated using AJAX can be stored using the JSON format on the web server. AJAX
is used so that javascript can retrieve these JSON files when necessary, parse them, and perform
one of the following operations :
Store the parsed values in the variables for further processing before displaying them on
the webpage.
It directly assigns the data to the DOM elements in the webpage, so that they are displayed
on the website.
The JSON Web Services on the web server in order to retrieve the details about the selected item.
The JSON web service would retrieve the data and convert into JSON and return a JSON string.
Instead of posting back to the server, the client would call the web service when an item was
selected from the list box.
{
"book": [ {
"id": "01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt"
},
{
"id": "07",
"language": "C++",
"edition": "second",
"author": "E.Balagurusamy"
} ] }
Example:1
<html> <head>
<title>the title</title>
<script type="text/javascript"
src="/jquery/jquery-1.3.2.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("#driver").click(function(event){
$.getJSON('/jquery/result.json', function(jd) {
$('#stage').html('<p> Name: ' + jd.name + '</p>');
$('#stage').append('<p>Age : ' + jd.age+ '</p>');
$('#stage').append('<p> Sex: ' + jd.sex+ '</p>');
}); }); });
</script> </head> <body>
<p>Click on the button to load result.html file:</p>
<div id="stage" style="background-color:blue;"> STAGE </div>
<input type="button" id="driver" value="Load Data" />
</body> </html>
JSON – DataTypes:
JSON format supports the following data types:
null empty
JSON – Objects:
Q) What are the JSON Objects and Explain?
Example
myObj = { "name":"John", "age":30, "car":null };
x = myObj.name;
Looping an Object:
Example
Modify Values:
Example
myObj.cars.car2 = "Mercedes";
Delete Object Properties:
Example
delete myObj.cars.car2;
Arrays as JSON Objects:
Example [ "Ford", "BMW", "Fiat" ]
Arrays in JSON are almost the same as arrays in JavaScript. In JSON, array values must be of type
string, number, object, array, boolean or null.
In JavaScript, array values can be all of the above, plus any other valid JavaScript expression,
including functions, dates, and undefined.
Example: {
"name":"John",
"age":30,
"cars":[ "Ford", "BMW", "Fiat" ] }
<html>
<head>
<title>Creating Object JSON with JavaScript</title>
<script language = "javascript" >
var JSONObj = { "name" : "tutorialspoint.com", "year" : 2005 };
document.write("<h1>JSON with JavaScript example</h1>");
document.write("<br>");
document.write("<h3>Website Name = "+JSONObj.name+"</h3>");
document.write("<h3>Year = "+JSONObj.year+"</h3>");
</script>
</head>
<body>
</body> </html>
To open Json Object using IE or any other javaScript enabled browser. It produces the result:
<html>
<head>
<title>Creation of array object in javascript using JSON</title>
<script language = "javascript" >
document.writeln("<h2>JSON array object</h2>");
var books = { "Pascal" : [
{ "Name" : "Pascal Made Simple", "price" : 700 },
{ "Name" : "Guide to Pascal", "price" : 400 }],
"Scala" : [
{ "Name" : "Scala for the Impatient", "price" : 1000 },
{ "Name" : "Scala in Depth", "price" : 1300 }]
}
var i = 0
document.writeln("<table border = '2'><tr>");
open Json Array Object using IE or any other javaScript enabled browser. It produces the result:
Step 1: Build a Data Grid Generator Class: We want to build a tool that will enable us to create
datagrids dynamically for any database table that we have. This means the code is not tied up to
any specific table structure, and, thus, is independent on the data itself. All the coder (the
developer who uses our class) must know is the name of the table to be transformed into a grid
and the primary key for that table. Here is the preface of the class that we will be developing for
the most part of this tutorial:
UNIT – V
ANGULAR - JS
Introduction: A basic understanding of JavaScript and any text editor. As we are going to develop
web-based applications using AngularJS, it will be good if we can an understanding of other web
technologies such as HTML, CSS, AJAX, etc.
The designed to help to learn AngularJS as quickly and efficiently as possible. First, we will
learn the basics of AngularJS: directives, expressions, filters, modules, and controllers. Then it will
learn everything else you need to know about AngularJS: Events, DOM, Forms, Input, Validation,
Http, and more. It is licensed under the Apache license version 2.0.
The History of AJS is:
AngularJS is an open source web application framework. It was originally developed in
2009 by Misko Hevery and Adam Abrons. It is now maintained by Google. Its latest version is 1.4.3.
The idea turned out very well, and the project is now officially supported by Google.
Q). What is AngularJS? What are the features of AngularJS and explain?
AngularJS is a very powerful JavaScript Framework. It is used in Single Page Application
(SPA) projects. It extends HTML DOM with additional attributes and makes it more responsive to
the user actions. [or]
AngularJS is a JavaScript framework. It can be added to an HTML page with a <script> tag.
AngularJS extends HTML attributes with Directives, and binds data to HTML with Expressions.
AngularJS is a framework used to build large scale and high performance web application
while keeping them as easy-to-maintain.
AngularJS is open source, completely free, and used by thousands of developers around the
world. It is licensed under the Apache license version 2.0.
Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 67
The Concept of Angular JS:
Features:
AngularJS is a powerful JavaScript based development framework to create RICH Internet
Application(RIA).
AngularJS provides developers options to write client side application (using JavaScript) in
a clean MVC(Model View Controller) way.
Application written in AngularJS is cross-browser compliant. AngularJS automatically
handles JavaScript code suitable for each browser.
AngularJS is open source, completely free, and used by thousands of developers around the
world. Its licensed under Apache License version 2.0.
Core Features:
The Following are most important core features of AngularJS:
Data-binding: It is the automatic synchronization of data between model and view
components.
Scope: The objects refers to the model. They act as a glue between controller and view.
Controller: JavaScript functions that are bound to a particular scope.
Services: AngularJS come with several built-in services for example $https: to make a
XMLHttpRequests.
Filters: To select a subset of items from an array and returns a new array.
Directives: Directives are markers on DOM elements (such as elements, attributes, css,
and more). These can be used to create custom HTML tags that serve as new, custom
widgets. AngularJS has built-in directives.
Templates − These are the rendered view with information from the controller and
model. These can be a single file (like index.html) or multiple views in one page using
"partials".
Routing: It is concept of switching views.
Disadvantages of AngularJS:
The AngularJS comes with lots of plus points but same time we should consider the following
points:
Not Secure − Being JavaScript only framework, application written in AngularJS are not
safe. Server side authentication and authorization is must to keep an application secure.
Not degradable − If your application user disables JavaScript then user will just see the
basic page and nothing more.
The AngularJS Components:
The AngularJS framework can be divided into following three major parts −
ng-app − This directive defines and links an AngularJS application to HTML.
ng-model − This directive binds the values of AngularJS application data to HTML input
controls.
ng-bind − This directive binds the AngularJS Application data to HTML tags.
Downloading AngularJS:
Q). Briefly Explain the Downloading Angular JS with example?
CDN access : Access to a CDN. The CDN will give a access around the world to regional data
centers, i.e Google host. This means using CDN moves the responsibility of hosting files from the
own servers to a series of external ones. The advantage AJS if the visitor to webpage has already
downloaded a copy of AngularJS from the same CDN, it won't have to be re-downloaded.
Try the new angularJS 2: Click on this button to download Angular JS beta 2 version.This version
is very fast, mobile supported and flexible compare to legacy and latest of AngularJS 1.We are
using the CDN versions.
Example: To write a simple example using AngularJS library. Let us create an HTML
file myfirstexample.html as below:
<!doctype html>
<html>
<head>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.5.2/angular.min.js"></script>
</head>
<body ng-app = "myapp">
<div ng-controller = "HelloController" >
<h2>Welcome {{helloTo.title}} to the world of Tutorialspoint!</h2>
</div>
<script>
angular.module("myapp", [])
.controller("HelloController", function($scope) {
$scope.helloTo = {};
$scope.helloTo.title = "AngularJS";
});
</script>
</body>
</html>
Include AngularJS:
<head>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
If you want to update into latest version of Angular JS, use the following script source or else
Check the latest version of AngularJS on their official website.
<head>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.5.2/angular.min.js"></script>
</head>
AngularJS directives are used to extend HTML. These are special attributes starting with ng-
prefix. The following directives are :
1. ng-app : This directive starts an AngularJS Application.
2. ng-init : This directive initializes application data.
3. ng-model : It binds the values of AngularJS application data to HTML input controls.
4. ng-repeat : This directive repeats html elements for each item in a collection.
1. ng-app directive:
ng-app directive starts an AngularJS Application. It defines the root element. It
automatically initializes or bootstraps the application when web page containing AngularJS
Application is loaded.
... </div>
2. ng-init directive:
ng-init directive initializes an AngularJS Application data. It is used to put values to the
variables to be used in the application. To initialize an array of countries. We're using JSON
syntax to define array of countries.
Example:
4. ng-repeat directive:
ng-repeat directive repeats html elements for each item in a collection. To iterated over
array of countries.
Example:
html>
<head>
<title>AngularJS Directives</title>
</head>
<body>
<h1>Sample Application</h1>
<div ng-app = "" ng-init = "countries = [{locale:'en-US',name:'United States'}, {locale:'en-GB',name:'United
Kingdom'}, {locale:'en-FR',name:'France'}]">
<p>Enter your Name: <input type = "text" ng-model = "name"></p>
<p>Hello <span ng-bind = "name"></span>!</p>
<p>List of Countries with locale:</p>
<ol>
<li ng-repeat = "country in countries">
{{ 'Country: ' + country.name + ', Locale: ' + country.locale }}
</li> </ol> </div>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</body> </html>
Result:
Sample Application
Hello !
Expressions are used to bind application data to html. Expressions are written inside
double braces like {{ expression}}. Expressions behaves in same way as ng-bind directives.
AngularJS application expressions are pure javascript expressions and outputs the data where
they are used. AngularJS expressions are much like JavaScript expressions: It contain literals,
operators, variables and etc.
Ex: {{ 5 + 5 }} or {{ firstName + " " + lastName }}
JavaScript expressions, AngularJS expressions can contain literals, operators, and variables.
JavaScript expressions, AngularJS expressions can be written inside HTML.
AngularJS expressions do not support conditionals, loops, and exceptions, while JavaScript
expressions do.
AngularJS expressions support filters, while JavaScript expressions do not.
AngularJS- Modules:
1. Application Module:
2. Controller Module:
To declared a controller studentController module using mainApp.controller function.
used application module using ng-app directive and controller using ng-controller
directive. Its imported mainApp.js and studentController.js in the main html page.
Example: Following example will showcase all the above mentioned modules.1. testAngularJS.htm
<html> <head>
<title>Angular JS Modules</title>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src = "/angularjs/src/module/mainApp.js"></script>
<script src = "/angularjs/src/module/studentController.js"></script>
<style>
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f2f2f2;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
</style> </head> <body>
<h2>AngularJS Sample Application</h2>
<div ng-app = "mainApp" ng-controller = "studentController">
<table border = "0">
<tr>
<td>Enter first name:</td>
<td><input type = "text" ng-model = "student.firstName"></td>
</tr>
<tr>
<td>Enter last name: </td>
<td><input type = "text" ng-model = "student.lastName"></td>
</tr>
<tr>
<td>Name: </td>
<td>{{student.fullName()}}</td>
</tr>
<tr>
<td>Subject:</td>
<td>
<table> <tr>
<th>Name</th>
<th>Marks</th>
</tr>
<tr ng-repeat = "subject in student.subjects">
<td>{{ subject.name }}</td>
<td>{{ subject.marks }}</td>
</tr>
</table> </td> </tr> </table> </div>
</body> </html>
2.mainApp.js
mainApp.controller("studentController", function($scope) {
$scope.student = {
firstName: "Mahesh",
lastName: "Parashar",
fees:500,
subjects:[
{name:'Physics',marks:70},
{name:'Chemistry',marks:80},
{name:'Math',marks:65},
{name:'English',marks:75},
{name:'Hindi',marks:67} ],
fullName: function() {
var studentObject;
studentObject = $scope.student;
return studentObject.firstName + " " + studentObject.lastName;
} }; });
Result:
Name Marks
Physics 70
Chemistry 80
Subject:
Math 65
English 75
Hindi 67
AngularJS – Controllers:
Q). Explain about Angular Controller with example?
AngularJS application mainly relies on controllers to control the flow of data in the
application. A controller is defined using ng-controller directive. A controller is a JavaScript object
<script>
function studentController($scope) {
$scope.student = {
firstName: "Mahesh",
lastName: "Parashar",
fullName: function() {
var studentObject;
studentObject = $scope.student;
return studentObject.firstName + " " + studentObject.lastName;
} }; } </script>
Angular – Scope:
Q). Explain about the Angular Scope with example?
Scope is a special javascript object which plays the role of joining controller with the views. Scope
contains the model data. In controllers, model data is accessed via $scope object. If we consider an
AngularJS application to consist of:
<script>
var mainApp = angular.module("mainApp", []);
mainApp.controller("shapeController", function($scope) {
$scope.message = "In shape controller";
$scope.type = "Shape";
});
</script>
Scope Inheritance:
Scope are controllers specific. If we defines nested controllers then child controller will inherit
the scope of its parent controller.
<script>
var mainApp = angular.module("mainApp", []);
mainApp.controller("shapeController", function($scope) {
$scope.message = "In shape controller";
$scope.type = "Shape";
});
mainApp.controller("circleController", function($scope) {
$scope.message = "In circle controller";
});
</script>
value
Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 77
factory
service
provider
constant
value : value is simple javascript object and it is used to pass values to controller during config
phase.
Factory: factory is a function which is used to return value. It creates value on demand whenever
a service or controller requires. It normally uses a factory function to calculate and return the
value.
Service: service is a singleton javascript object containing a set of functions to perform certain
tasks. Services are defined using service() functions and then injected into controllers.
Provider: provider is used by AngularJS internally to create services, factory etc. during config
phase(phase during which AngularJS bootstraps itself). Provider is a special factory method with
a method get() which is used to return the value/service/factory.
Constant : constants are used to pass values at config phase considering the fact that value can not
be used to be passed during config phase.
Example:
<html>
<head>
<title>AngularJS Dependency Injection</title>
</head> <body>
<h2>AngularJS Sample Application</h2>
<div ng-app = "mainApp" ng-controller = "CalcController">
<p>Enter a number: <input type = "number" ng-model = "number" /></p>
<button ng-click = "square()">X<sup>2</sup></button>
<p>Result: {{result}}</p>
</div> <script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.config(function($provide) {
$provide.provider('MathService', function() {
this.$get = function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b;
} return factory;
}; }); });
mainApp.value("defaultInput", 5);
mainApp.factory('MathService', function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b;
} return factory;
});
mainApp.service('CalcService', function(MathService){
this.square = function(a) {
return MathService.multiply(a,a);
Result: 25
Angular filters are a way of processing data and returning a specific set of logic. It can be
absolutely anything, from processing a date stamp into a formatted time, to a list of names that
begin with a specific letter.
Filters are used to change modify the data and can be clubbed in expression or directives
using pipe character. Following is the list of commonly used filters.
Filters can be used in two different ways, 1. the DOM via a pipe | character inside our
expressions, which Angular parses. 2. The second way is using the $filter Service, which we can
dependency inject and use within our JavaScript instead of HTML.
The Angular's built-in filters are:
Single value Filters
Data set Filters
Date filters
JSON filter
limitTo and orderBy
Controller ($scope) Filters
Example:
function SomeCtrl () {
this.namesStartingWithA = function () {
}; }
AngularJS Events:
To add AngularJS event listeners to your HTML elements by using one or more of these
directives:
ng-blur
ng-change
ng-click
ng-copy
ng-cut
ng-dblclick
ng-focus
ng-keydown
ng-keypress
ng-keyup
ng-mousedown
ng-mouseenter
ng-mouseleave
ng-mousemove
ng-mouseover
ng-mouseup
ng-paste
The event directives allows us to run AngularJS functions at certain user events. An AngularJS
event will not overwrite an HTML event, both events will be executed.
Mouse Events: Mouse events occur when the cursor moves over an element, in this order:
1. ng-mouseenter
2. ng-mouseover
3. ng-mousemove
4. ng-mouseleave
1. ng-mousedown
2. ng-mouseup
3. ng-click
Example: Increase the count variable when the mouse moves over the H1 element:
<div ng-app="myApp" ng-controller="myCtrl">
<h1 ng-mousemove="count = count + 1">Mouse over me!</h1>
Storing data
Generating data structures from user input
Transferring data from server to client, client to server, and server to server
Configuring and verifying data
To provide with an introduction to working with JSON in JavaScript. To make the most use of this
introduction, it should have some familiarity with the JavaScript programming language.
JSON Format
JSON’s format is derived from JavaScript object syntax, but it is entirely text-based. It is a key-
value data format that is typically rendered in curly braces.
function process(argv) {
filter(callback[, Creates a new array with all of the elements of this array for which the provided
thisObject]) filtering function returns true. If a thisObject parameter is provided to filter, it will
be used as the this for each invocation of the callback. IE9
forEach(callback[ Calls a function for each element in the array.
, thisObject])
map(callback[, Creates a new array with the results of calling a provided function on every
thisObject]) element in this array.
filter(), map() and forEach() all call a callback with every value of the array. This can be useful for
performing various operations on the array.
var b = [ 1, 2, 3 ];
console.log( a.concat(['d', 'e', 'f'], b) );
console.log( a.join('! ') );
console.log( a.slice(1, 3) );
console.log( a.reverse() );
console.log( ' --- ');
var c = a.splice(0, 2);
console.log( a, c );
var d = b.splice(1, 1, 'foo', 'bar');
console.log( b, d );
<html>
<head>
<title>The Selecter Example</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
/* This would select second division only*/
$("#div2").css("background-color", "yellow");
});
RESULT:
This will produce the following result:
This is first division of the DOM.
This is second division of the DOM.
This is third division of the DOM
Result:
<html>
<head>
<title>the title</title>
Result:
<html>
<head>
<title>the title</title>
<script type="text/javascript"
src="/jquery/jquery-1.3.2.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function(){
var mappedItems = $("li").map(function (index) {
var replacement = $("<li>").text($(this).text()).get(0);
if (index == 0) {
// make the first item all caps
$(replacement).text($(replacement).text().toUpperCase());
} else if (index == 1 || index == 3) {
// delete the second and fourth items
replacement = null;
} else if (index == 2) {
// make two of the third item and add some text
replacement = [replacement,$("<li>").get(0)];
$(replacement[0]).append("<b> - A</b>");
$(replacement[1]).append("Extra <b> - B</b>");
}
// replacement will be an dom element, null,
// or an array of dom elements
return replacement;
});
$("#results").append(mappedItems);
});
</script>
<style>
body { font-size:16px; }
ul { float:left; margin:0 30px; color:blue; }
Result:
<html>
<head>
<title>the title</title>
<script type="text/javascript"
src="/jquery/jquery-1.3.2.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("div").click(function () {
var color = $(this).css("background-color");
$("#result").html("That div is <span>" + color + "</span>.");
$("#result").css({'color': color,
'font-weight' : 'bold',
'background-color': 'gray'});
});
});
</script>
<style>
div { width:60px; height:60px; margin:5px; float:left; }
</style>
</head>
<body>
<p>Click on any square:</p>
<span id="result"> </span>
<div style="background-color:blue;"></div>
<div style="background-color:rgb(15,99,30);"></div>
<div style="background-color:#123456;"></div>
<div style="background-color:#f11;"></div>
</body>
</html>
Result:
<html>
<head>
<title>the title</title>
<script type="text/javascript"
src="/jquery/jquery-1.3.2.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function(){
$("div.demo").scrollLeft( 200 );
$("div.demo").mousemove(function () {
var left = $("div.demo").scrollLeft();
$("#result").html("left offset: <span>" +
left + "</span>.");
});
});
</script>
<style>
div.demo {
background:#CCCCCC none repeat scroll 0 0;
border:3px solid #666666;
margin:5px;
padding:5px;
position:relative;
width:200px;
height:100px;
overflow:auto;
}
div.result{
margin:10px;
width:100px;
height:100px;
margin:5px;
float:left;
background-color:blue;
}
p { margin:10px;
padding:5px;
border:2px solid #666;
width:1000px;
height:1000px;
}
</style>
</head>
<body>
<div class="demo"><p>Hello</p></div>
<span>Scroll horizontal button to see the result:</span>
<div class="result"><span id="result"></span></div>
</body>
</html>
DOM Manipulation:
11. DOM Elements – WrapAll() Method
11. Write a JQuery program to perform an Inserting DOM Elements using wrapAll( html )
Method?
<html>
<head>
<title>the title</title>
<script type="text/javascript"
src="/jquery/jquery-1.3.2.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("div").click(function () {
var content = "<div class='div'></div>";
$("div").wrapAll( content );
});
});
</script>
<style>
.div{ margin:10px;padding:12px;
border:2px solid #666;
width:60px;
}
</style>
</head>
<body>
<p>Click on any square below to see the result:</p>
<div class="div" id="destination">THIS IS TEST</div>
<div class="div" style="background-color:blue;">ONE</div>
<div class="div" style="background-color:green;">TWO</div>
<div class="div" style="background-color:red;">THREE</div>
</body>
</html>
Result:
13. Write a JQuery program to implement Event Manipulation Methods i.e off( events [,
selector ] [, handler(eventObject) ] ) and on() method?
<html>
<head>
<title>The jQuery Example</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
function aClick() {
$("div").show().fadeOut("slow");
}
$("#bind").click(function () {
$("#theone").on("click", aClick).text("Can Click!");
});
$("#unbind").click(function () {
$("#theone").off("click", aClick).text("Does nothing...");
});
});
</script>
<style>
button { margin:5px; }
button#theone { color:red; background:yellow; }
</style>
</head>
<body>
<button id="theone">Does nothing...</button>
<button id="bind">Bind Click</button>
<button id="unbind">Unbind Click</button>
<div style="display:none;">Click!</div>
</body>
</html>
Result:
Click on any square below to see the result:
Result:
15.Write a JQuery program to perform the Passing Data to the Server using AJAX?
<html>
<head>
<title>the title</title>
<script type="text/javascript"
src="/jquery/jquery-1.3.2.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("#driver").click(function(event){
var name = $("#name").val();
$("#stage").load('/jquery/result.php', {"name":name} );
});
});
</script>
</head>
<body>
<p>Enter your name and click on the button:</p>
<input type="input" id="name" size="40" /><br />
<div id="stage" style="background-color:blue;">
<?php
if( $_REQUEST["name"] )
{
$name = $_REQUEST['name'];
echo "Welcome ". $name;
}
?>
16. Write a JQuery program to implement GET DATA using serializeArray( ) Method in
AJAX ?
<?php
if( $_REQUEST["name"] )
{
$name = $_REQUEST['name'];
echo "Welcome ". $name;
$age = $_REQUEST['age'];
echo "<br />Your age : ". $age;
$sex = $_REQUEST['sex'];
echo "<br />Your gender : ". $sex;
}
?>
<html>
<head>
<title>The jQuery Example</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("#driver").click(function(event){
$.post(
"serialize.php",
$("#testform").serializeArray(),
function(data) {
$('#stage1').html(data);
}
Advanced Java Script- JQUERY III- B.Sc(VI-Sem) Page 98
);
var fields = $("#testform").serializeArray();
$("#stage2").empty();
jQuery.each(fields, function(i, field){
$("#stage2").append(field.value + " ");
});
});
});
</script>
</head>
<body>
<p>Click on the button to load result.html file:</p>
<div id="stage1" style="background-color:blue;">
STAGE - 1
</div>
<br />
<div id="stage2" style="background-color:blue;">
STAGE - 2
</div>
<form id="testform">
<table>
<tr>
<td><p>Name:</p></td>
<td><input type="text" name="name" size="40" /></td>
</tr>
<tr>
<td><p>Age:</p></td>
<td><input type="text" name="age" size="40" /></td>
</tr>
<tr>
<td><p>Sex:</p></td>
<td> <select name="sex">
<option value="Male" selected>Male</option>
<option value="Female" selected>Female</option>
</select></td>
</tr>
<tr>
<td colspan="2">
<input type="button" id="driver" value="Load Data" />
</td> </tr> </table> </form> </body>
</html>
Result:
EFFECTS:
17. Write a JQuery program to perform the JQuery Effects using Showing and Hiding
Elements?
<html>
<head>
<title>The jQuery Example</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("#show").click(function () {
$(".mydiv").show( 1000 );
});
$("#hide").click(function () {
$(".mydiv").hide( 1000 );
}); });
</script>
<style>
.mydiv{ margin:10px;padding:12px; border:2px solid #666; width:100px;
height:100px;}
</style> </head>
<body>
<div class="mydiv">
This is a SQUARE
</div>
<input id="hide" type="button" value="Hide" />
<input id="show" type="button" value="Show" />
</body> </html>
Result:
Result: