jQuery
Basics - Getting Started
So what is jQuery? From the jQuery
web site: "jQuery is a fast and concise موجز JavaScript Library that simplifies HTML document traversing اجتياز, event handling, animating, and Ajax
interactions for rapid تسريع web development. jQuery is designed to
change the way that you write JavaScript." jQuery will help you write JavaScript faster using a simpler
syntax. Instead of writing extra lines of code or the writing the same code
over and over, you can use jQuery to consolidate تعزيز the code. jQuery will do the heavy lifting
while you can concentrate on the more important stuff. jQuery also supports the
idea of plugins. Plugins allow people to create mini-libraries that complement
jQuery. The plugins can be anything from form validation to picture slide
shows. We will look at plugins in future articles.
Where to Start
The first thing you will need to do to start using jQuery is to
decide if you want to host the jQuery library or use a content delivery network
(CDN). If you plan on hosting the jQuery library, you will need to download it
from the jQuery web site (http://jquery.com) and upload it to your web server. The
best way to use jQuery is to use a CDN. Both Microsoft and Google offer jQuery
on their CDNs. There are several advantages to doing this. The first is that a
CDN is spread out over the Internet. When someone comes to your web site and
requests the jQuery library, it will be provided to them by the closestالاقرب hosting site. This will help speed up the
download of the library to their local machine. Which brings us to another
point, the jQuery library is cached on the user's machine to help with speed. The
second reason is that if the user has been to another web site that had this
CDN reference, the user will already have the jQuery file on their system. This
will speed up the loading of your web page since they will not need to download
the file again.When you are looking at the different libraries for jQuery, you
will notice there are two. One of them has a ".min" in the file name.
This is a "minified" version of the file. It is smaller and will load
faster. Why two versions? The non-minified version is easier to read, but since
there is a lot of white space, it makes the file larger. It is used to help
with debugging. So whenever possible, always use the CDN and the minified
version. This will help speed up your web site.Next we need to create a
reference to the jQuery library. This is done by adding a line in between the
opening (<head>) and closing (</head>) HTML header tags. We will
use the Microsoft CDN.
<head>
<script
type="text/javascript"
src="https://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js"></script>
</head>
jQuery works like normal JavaScript in the fact that you use
<script> tags to denote the script. These can be placed in the head
section or the body section of your web page.
<script>
Your script goes here
</script>
</script>
<script type="text/javascript">
</script>
</head>
<body>
<a href="#">Click Me</a>
</body>
</html>
Currently, the link "Click Me" does nothing. Let us change
that. Enter the code below in between the script tags.
$(document).ready(function(){
$("a").click(function(event){
alert("You clicked me!");
});
});
What we did here was add a click event to the "Click Me"
link. When it was clicked, it showed a JavaScript alert.
What is Up with the $
The dollar sign ($) denotes a jQuery
constructor. It can be written either as $() or jQuery(). The dollar sign is
just a shortcut. All jQuery constructors must start with this.The constructor
starts with a $ and the selector is enclosed in parenthesis. A selector can be
an element (tag), an element ID, an element class name. This is similar to the
way CSS works. In the example above, we used the anchor tag (a) as a selector.
When you use a selector, jQuery searches through the Document Object Model
(DOM) to find all selectors that match. In the case of the example above, if we
had more than one anchor tag, all anchor tags would now have a click event. Since
selectors work similar to CSS, you will need to specify the selectors in a
similar way. When referencing HTML elements, you will just use the element as
is. See the following examples:
$("a") - all anchor tags
$("p") - all paragraph tags
$("p.subject") - all paragraph tags with a class of subject
When referencing class names, you
must specify the period (.) before the class name as in the following examples:
$(".subject") - all elements with the class name of subject
$("p.subject") - all paragraph tags with a class of subject
And last, when referencing IDs, you must specify the # before the ID
name:
$("#subject") - the element with the ID of subject
There are a few other types of
selectors and we will talk about those in future articles. For now, these basic
selectors should get you started.
Making Sure the Document is Ready
As with JavaScript, you may want to execute your jQuery code after
the HTML document has completely loaded and is ready to be manipulated. This is
where the $(document).ready function comes in to play. This will keep the
JavaScript and jQuery code unloaded until the document is ready. Once the
document has loaded, the function will execute. This keeps the code from
executing before the document is ready which could cause issues. If you tried
to manipulate a DOM element before it was ready, you would lose that
functionality.
Conclusion
This article should be able to get you started using jQuery. The
great thing about jQuery is that is does not replace JavaScript, just makes it
better. Check back later as we will dive deeper into jQuery.
Adding jQuery to Your Web Pages
There are several ways to start using jQuery on your web site. You
can:
- Download the jQuery library from jQuery.com
- Include jQuery from a CDN, like Google
Downloading jQuery
There are two versions of jQuery available for downloading:
- Production version - this is for your live website because it has been minified and compressed
- Development version - this is for testing and development (uncompressed and readable code)
Both versions can be downloaded from jQuery.com. The jQuery
library is a single JavaScript file, and you reference it with the HTML
<script> tag (notice that the <script> tag should be inside the
<head> section):
<head>
<script src="jquery-1.10.2.min.js"></script>
</head>
<script src="jquery-1.10.2.min.js"></script>
</head>
Alternatives to Downloading
If you don't want to download and
host jQuery yourself, you can include it from a CDN (Content Delivery Network).
Both Google and Microsoft host jQuery. To use jQuery from Google or Microsoft,
use one of the following:
Google CDN:
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
</head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
</head>
jQuery Syntax
The jQuery syntax is tailor made for selecting HTML elements
and performing some action on the element(s).
Basic syntax is: $(selector).action()
- A $ sign to define/access jQuery
- A (selector) to "query (or find)" HTML elements
- A jQuery action() to be performed on the element(s)
Examples:
$(this).hide() - hides the current element.
$("p").hide() - hides all <p> elements.
$(".test").hide() - hides all elements with
class="test".
$("#test").hide() - hides the element with
id="test".
The Document Ready Event
You might have noticed that all jQuery methods in our examples, are
inside a document ready event:
$(document).ready(function(){
// jQuery methods go here...
});
// jQuery methods go here...
});
This is to prevent any jQuery code from running before the document
is finished loading (is ready). It is good practice to wait for the document to
be fully loaded and ready before working with it. This also allows you to have
your JavaScript code before the body of your document, in the head
section. Here are some examples of
actions that can fail if methods are run before the document is fully loaded: Trying
to hide an element that is not created yet Trying to get the size of an image
that is not loaded yet Tip: The jQuery team has also created an even
shorter method for the document ready event:
$(function(){
// jQuery methods go here...
});
// jQuery methods go here...
});
jQuery Selectors
jQuery selectors allow you to select
and manipulate HTML element(s). jQuery selectors are used to "find"
(or select) HTML elements based on their id, classes, types, attributes, values
of attributes and much more. It's based on the existing CSS Selectors, and
in addition, it has some own custom selectors. All selectors in jQuery start
with the dollar sign and parentheses: $().
The element Selector
The jQuery element selector selects
elements based on the element name. You can select all <p> elements on a
page like this:
$("p")
Example
When a user clicks on a button, all <p> elements will be
hidden:
<!DOCTYPE html>
<html><head>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
</script></head>
<body>
<h2>This is a
heading</h2>
<p>This is a
paragraph.</p>
<p>This is another
paragraph.</p>
<button>Click
me</button>
</body></html>
The #id Selector
The jQuery #id selector uses the id attribute of an HTML tag to find
the specific element. An id should be unique within a page, so you should use
the #id selector when you want to find a single, unique element. To find an
element with a specific id, write a hash character, followed by the id of the
element: $("#test")
Example: When a user clicks on a button, the element with
id="test" will be hidden:
The .class Selector
The jQuery class selector finds elements with a specific class. To
find elements with a specific class, write a period character, followed by the
name of the class: $(".test")
Example: When a user clicks on a button, the elements with
class="test" will be hidden:
Functions In a Separate File
If your website contains a lot of pages, and you want your jQuery
functions to be easy to maintain, you can put your jQuery functions in a
separate .js file. When we demonstrate jQuery in this tutorial, the functions
are added directly into the <head> section. However, sometimes it is
preferable to place them in a separate file, like this (use the src attribute
to refer to the .js file):
Example
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="my_jquery_functions.js"></script></head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="my_jquery_functions.js"></script></head>
What are Events?
All the different visitor's actions that a web page can respond to
are called events. An event represents the precise moment when something
happens. Examples:
- moving a mouse over an element
- selecting a radio button
- clicking on an element
The term "fires" is often used with events.
Example: "The keypress event fires the moment you press a key".
Here are some common DOM events:
Mouse Events
|
Keyboard Events
|
Form Events
|
Document/Window Events
|
click
|
keypress
|
submit
|
load
|
dblclick
|
keydown
|
change
|
resize
|
mouseenter
|
keyup
|
focus
|
scroll
|
mouseleave
|
blur
|
unload
|
jQuery Syntax For Event Methods
In jQuery, most DOM events have an
equivalent jQuery method. To assign a click event to all paragraphs on a page,
you can do this: $("p").click();
The next step is to define what should happen when the event fires. You must
pass a function to the event:
$("p").click(function(){
// action goes here!!
});
// action goes here!!
});
dblclick()
The dblclick() method attaches an event handler function to an HTML
element. The function is executed when the user double-clicks on the HTML
element: Example
$("p").dblclick(function(){
$(this).hide();
});
$(this).hide();
});
mouseenter()
The mouseenter() method attaches an event handler function
to an HTML element. The function is executed when the mouse pointer enters the
HTML element:
<!DOCTYPE html>
<head>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#p1").mouseenter(function(){
alert("You entered p1!");
});
});
</script></head>
<body>
<p
id="p1">Enter this paragraph.</p>
</body></html>
mouseleave()
The mouseleave() method attaches an event handler function to an
HTML element.
The function is executed when the mouse pointer leaves the HTML
element: Example
$("#p1").mouseleave(function(){
alert("Bye! You now leave p1!");
});
alert("Bye! You now leave p1!");
});
mousedown()
The mousedown() method attaches an event handler function to
an HTML element. The function is executed, when the left mouse button is
pressed down, while the mouse is over the HTML elemen
hover()
The hover() method takes two functions and is a combination of the
mouseenter() and mouseleave() methods. The first function is executed when the
mouse enters the HTML element, and the second function is executed when the
mouse leaves the HTML element: Example
$("#p1").hover(function(){
alert("You entered p1!");
},
function(){
alert("Bye! You now leave p1!");
});
alert("You entered p1!");
},
function(){
alert("Bye! You now leave p1!");
});
focus()
The focus() method attaches an event handler function to an
HTML form field. The function is executed when the form field gets focus:
blur()
The blur() method attaches an event handler function to an
HTML form field. The function is executed when the form field loses focus:
<!DOCTYPE html>
<head>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("input").focus(function(){
$(this).css("background-color","#cccccc");
});
$("input").blur(function(){
$(this).css("background-color","#ffffff");
});
});
</script></head>
<body>
Name: <input
type="text" name="fullname"><br>
Email: <input
type="text" name="email">
</body></html>
jQuery hide() and show()
With jQuery, you can hide and show HTML elements with the hide() and
show() methods:
<!DOCTYPE html><head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#hide").click(function(){
$("p").hide();
});
$("#show").click(function(){
$("p").show();
});
});
</script></head>
<body>
<p>If you click on the "Hide" button, I will
disappear.</p>
<button id="hide">Hide</button>
<button id="show">Show</button>
</body></html>
Syntax: $(selector).hide(speed,callback);
$(selector).show(speed,callback);
The optional speed parameter specifies the speed of the
hiding/showing, and can take the following values: "slow",
"fast", or milliseconds. The optional callback parameter is a
function to be executed after the hide() or show() method completes (you will
learn more about callback functions in a later chapter). The following example
demonstrates the speed parameter with hide():
<!DOCTYPE html>
<head>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").hide(1000);
});
});
</script></head>
<body>
<button>Hide</button>
<p>This is a paragraph with
little content.</p> <p>This is another small paragraph.</p>
</body></html>
jQuery toggle()
With jQuery, you can toggle between
the hide() and show() methods with the toggle() method. Shown elements are
hidden and hidden elements are shown:
$("button").click(function(){
$("p").toggle();
});
$("p").toggle();
});
$(selector).toggle(speed,callback);
jQuery Effects - Fading
With jQuery you can fade elements in and out of visibility.
<!DOCTYPE html>
<head><script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script><script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").fadeIn();
$("#div2").fadeIn("slow");
$("#div3").fadeIn(3000);
});
});
</script></head>
<body>
<p>Demonstrate fadeIn() with
different parameters.</p><button>Click to fade in
boxes</button>
<br><br>
<div id="div1"
style="width:80px;height:80px;display:none;background-color:red;"></div><br>
<div id="div2"
style="width:80px;height:80px;display:none;background-color:green;"></div><br>
<div id="div3"
style="width:80px;height:80px;display:none;background-color:blue;"></div>
</body></html>
Effects - Sliding
<!DOCTYPE html>
<head><script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideDown("slow");
});
});
</script>
<style type="text/css">
#panel,#flip
{
padding:5px;
text-align:center;
background-color:#e5eecc;
border:solid 1px #c3c3c3;
}
#panel
{
padding:50px;
display:none;
}
jQuery Sliding Methods
With jQuery you can create a sliding effect on elements. jQuery has
the following slide methods:
- slideDown()
- slideUp()
- slideToggle()
The jQuery animate() method lets you create custom animations.
jQuery Animations - The animate() Method
The jQuery animate() method is used to create custom animations.
Syntax: $(selector).animate({params},speed,callback);
The required params parameter defines
the CSS properties to be animated. 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 animation completes. The following example
demonstrates a simple use of the animate() method; it moves a <div>
element to the left, until it has reached a left property of 250px:
<!DOCTYPE html><head>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script><script>
$(document).ready(function(){
$("button").click(function(){
$("div").animate({left:'250px'});
});
</script> </head>
<body><button>Start Animation</button>
<p>By default, all HTML
elements have a static position, and cannot be moved. To manipulate the
position, remember to first set the CSS position property of the element to
relative, fixed, or absolute!</p>
<div
style="background:#98bf21;height:100px;width:100px;position:absolute;">
</div></body></html>
jQuery animate() - Manipulate Multiple Properties
Notice that multiple properties can be animated at the same time:
Example
$("button").click(function(){
$("div").animate({
left:'250px',
opacity:'0.5',
height:'150px',
width:'150px'
});
});
$("div").animate({
left:'250px',
opacity:'0.5',
height:'150px',
width:'150px'
});
});
jQuery animate() - Using Relative Values
It is also possible to define relative values (the value is then
relative to the element's current value). This is done by putting += or -= in
front of the value:
Example
$("button").click(function(){
$("div").animate({
left:'250px',
height:'+=150px',
width:'+=150px'
});
});
$("div").animate({
left:'250px',
height:'+=150px',
width:'+=150px'
});
});
jQuery animate() - Using Pre-defined Values
You can even specify a property's animation value as
"show", "hide", or "toggle":
Example
$("button").click(function(){
$("div").animate({
height:'toggle'
});
});
$("div").animate({
height:'toggle'
});
});
jQuery animate() - Uses Queue Functionality
By default, jQuery comes with queue
functionality for animations. This means that if you write multiple animate()
calls after each other, jQuery creates an "internal" queue with these
method calls. Then it runs the animate calls ONE by ONE. So, if you want to
perform different animations after each other, we take advantage of the queue
functionality:
<!DOCTYPE html><head>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script><script>
$(document).ready(function(){
$("button").click(function(){
var div=$("div");
div.animate({height:'300px',opacity:'0.4'},"slow");
div.animate({width:'300px',opacity:'0.8'},"slow");
div.animate({height:'100px',opacity:'0.4'},"slow");
div.animate({width:'100px',opacity:'0.8'},"slow");
});
});
</script> </head><body><button>Start
Animation</button>
<p>By default, all HTML
elements have a static position, and cannot be moved. To manipulate the
position, remember to first set the CSS position property of the element to
relative, fixed, or absolute!</p>
<div
style="background:#98bf21;height:100px;width:100px;position:absolute;"></div></body></html>
The example below first moves the <div> element to the right,
and then increases the font size of the text:
Example 2
<!DOCTYPE html>
<head><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script><script>
$(document).ready(function(){
$("button").click(function(){
var
div=$("div");
div.animate({left:'100px'},"slow");
div.animate({fontSize:'3em'},"slow");
});
});
</script> </head><body><button>Start
Animation</button>
<p>By default, all HTML elements have a static position, and
cannot be moved. To manipulate the position, remember to first set the CSS
position property of the element to relative, fixed, or absolute!</p>
<div style="background:#98bf21;height:100px;width:200px;position:absolute;">HELLO</div></body></html>
The jQuery stop() method is used to stop animations or effects before it
is finished.
jQuery stop() Method
The jQuery stop() method is used to stop an animation or effect
before it is finished. The stop() method works for all jQuery effect functions,
including sliding, fading and custom animations.
Syntax:
$(selector).stop(stopAll,goToEnd);
The optional stopAll parameter specifies whether also the animation
queue should be cleared or not. Default is false, which means that only the
active animation will be stopped, allowing any queued animations to be
performed afterwards. The optional goToEnd parameter specifies whether or not
to complete the current animation immediately. Default is false. So, by
default, the stop() method kills the current animation being performed on the
selected element. The following example demonstrates the stop() method, with no
parameters:
<!DOCTYPE html><head>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script><script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideDown(5000);
});
$("#stop").click(function(){
$("#panel").stop();
});
});
</script> <style
type="text/css">
#panel,#flip
{
padding:5px;
text-align:center;
background-color:#e5eecc;
border:solid 1px #c3c3c3;
}
#panel
{
padding:50px;
display:none;
}
</style></head><body>
<button id="stop">Stop sliding</button><div
id="flip">Click to slide down panel</div>
<div
id="panel">Hello world!</div>
</body></html>
A callback function is executed after the current effect
is 100% finished.
jQuery Callback Functions
JavaScript statements are executed line by line. However, with
effects, the next line of code can be run even though the effect is not finished.
This can create errors. To prevent this, you can create a callback function.
A callback function is executed after
the current effect is finished.Typical syntax: $(selector).hide(speed,callback);
Examples
The example below has a callback
parameter that is a function that will be executed after the hide effect is
completed:
<!DOCTYPE html><head><script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script><script>
$(document).ready(function(){
$("button").click(function(){
$("p").hide("slow",function(){
alert("The paragraph is
now hidden");
});
});
});</script></head><body><button>Hide</button><p>This
is a paragraph with little content.</p></body></html>
<!DOCTYPE html><html><head><script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").hide("slow",function(){
alert("The paragraph is now
hidden");
});
});
});</script></head><body><button>Hide</button><p>This
is a paragraph with little content.</p></body></html>
The example below has no callback parameter, and the alert box will be
displayed before the hide effect is completed:
<!DOCTYPE html>
<html><head><script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script><script>
$(document).ready(function(){
$("button").click(function(){
$("p").hide(1000);
alert("The paragraph is now hidden");
});
});</script></head><body><button>Hide</button><p>This
is a paragraph with little content.</p></body></html>
With jQuery, you can chain
together actions/methods. Chaining allows us to run multiple jQuery methods (on
the same element) within a single statement.
jQuery Method Chaining
Until now we have been writing jQuery
statements one at a time (one after the other). However, there is a technique
called chaining, that allows us to run multiple jQuery commands, one after the
other, on the same element(s). Tip: This way, browsers do not have to
find the same element(s) more than once.To chain an action, you simply append
the action to the previous action. The
following example chains together the css(), slideUp(), and slideDown()
methods. The "p1" element first changes to red, then it slides up,
and then it slides down:
<!DOCTYPE html><html><head><script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function()
{
$("button").click(function(){
$("#p1").css("color","red").slideUp(2000).slideDown(2000);
});
});</script></head><body><p
id="p1">jQuery is fun!!</p><button>Click
me</button></body></html>
We could also have added more method calls if needed. Tip:
When chaining, the line of code could become quite long. However, jQuery is not
very strict on the syntax; you can format it like you want, including line
breaks and indentations. This also works
just fine:
<!DOCTYPE html><html><head><script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function()
{
$("button").click(function(){
$("#p1").css("color","red")
.slideUp(2000)
.slideDown(2000);
});
});
</script></head><body><p
id="p1">jQuery is fun!!</p><button>Click
me</button></body></html>
jQuery contains powerful methods for changing and
manipulating HTML elements and attributes.
jQuery DOM Manipulation
One very important part of jQuery is the possibility to manipulate
the DOM.
jQuery comes with a bunch of DOM related methods that make it easy
to access and manipulate elements and attributes.DOM = Document Object Model
The DOM defines a standard for accessing HTML and XML 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 DOM defines a standard for accessing HTML and XML 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."
Get Content - text(), html(), and val()
Three simple, but useful, jQuery methods for DOM manipulation are:
- text() - Sets or returns the text content of selected elements
- html() - Sets or returns the content of selected elements (including HTML markup)
- val() - Sets or returns the value of form fields
The following example demonstrates how to get content with the
jQuery text() and html() methods:
<!DOCTYPE
html><head><script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script><script>
$(document).ready(function(){
$("#btn1").click(function(){
alert("Text: " + $("#test").text());
});
$("#btn2").click(function(){
alert("HTML: " + $("#test").html());
});
});
</script></head><body><p
id="test">This is some <b>bold</b> text in a
paragraph.</p>
<button
id="btn1">Show Text</button><button
id="btn2">Show HTML</button>
</body></html>
The following example demonstrates how to get the value of an input
field with the jQuery val() method:
<!DOCTYPE html>
<head>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
alert("Value: " + $("#test").val());
});
});
</script></head>
<body>
<p>Name: <input type="text"
id="test" value="Mickey Mouse"></p>
<button>Show
Value</button></body></html>
Get Attributes - attr()
The jQuery attr() method is used to get attribute values.
<!DOCTYPE html>
<html>
<head>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
alert($("#w3s").attr("href"));
});
});
</script></head>
<body>
<p><a
href="http://www.w3schools.com"
id="w3s">W3Schools.com</a></p>
<button>Show href
Value</button></body></html>
Set Content - text(), html(), and val()
We will use the same three methods from the previous page to set
content:
- text() - Sets or returns the text content of selected elements
- html() - Sets or returns the content of selected elements (including HTML markup)
- val() - Sets or returns the value of form fields
<!DOCTYPE html>
<head><script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("#test1").text("Hello world!");
});
$("#btn2").click(function(){
$("#test2").html("<b>Hello world!</b>");
});
$("#btn3").click(function(){
$("#test3").val("Dolly Duck");
});
});
</script></head>
<body>
<p id="test1">This
is a paragraph.</p>
<p id="test2">This
is another paragraph.</p>
<p>Input field: <input
type="text" id="test3" value="Mickey
Mouse"></p>
<button
id="btn1">Set Text</button>
<button
id="btn2">Set HTML</button>
<button
id="btn3">Set Value</button></body></html>
A Callback Function for text(), html(), and val()
All of the three jQuery methods above: text(), html(), and val(),
also come with a callback function. The callback function has two parameters:
the index of the current element in the list of elements selected and the
original (old) value. You then return the string you wish to use as the new
value from the function.
<!DOCTYPE html>
<html>
<head><script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("#test1").text(function(i,origText){
return "Old text: " + origText
+ " New text: Hello world! (index: " + i + ")";
});
});
$("#btn2").click(function(){
$("#test2").html(function(i,origText){
return "Old html: " + origText
+ " New html: Hello <b>world!</b> (index: " + i +
")";
});
});
});
</script></head>
Set Attributes - attr()
The jQuery attr() method is also used to set/change attribute
values.
$("button").click(function(){
$("#w3s").attr("href","http://www.w3schools.com/jquery");
});
$("#w3s").attr("href","http://www.w3schools.com/jquery");
});
The attr() method also allows you to set multiple attributes
at the same time.
The following example demonstrates how to set both the href
and title attributes at the same time:
<!DOCTYPE html>
<head><script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#w3s").attr({
"href" :
"http://www.w3schools.com/jquery",
"title" : "W3Schools
jQuery Tutorial"
});
});
});
</script></head>
<body>
<p><a
href="http://www.w3schools.com"
id="w3s">W3Schools.com</a></p>
<button>Change href and
title</button>
<p>Mouse over the link to
see that the href attribute has changed and a title attribute is set.</p>
</body></html>
A Callback Function for attr()
The jQuery method attr(), also come with a callback function. The
callback function has two parameters: the index of the current element in the
list of elements selected and the original (old) attribute value. You then
return the string you wish to use as the new attribute value from the function.
The following example demonstrates attr() with a callback function:
Example
$("button").click(function(){
$("#w3s").attr("href", function(i,origValue){
return origValue + "/jquery";
});
});
$("#w3s").attr("href", function(i,origValue){
return origValue + "/jquery";
});
});
No comments:
Post a Comment