Wednesday, August 25, 2010

HTML, Java Script and JQuery

HTML

HTML, which stands for HyperText Markup Language, is the predominant markup language for web pages. It provides a means to create structured documents by denoting structural semantics for text such as headings, paragraphs, lists, links, quotes and other items. It allows images and objects to be embedded and can be used to create interactive forms. It is written in the form of HTML elements consisting of "tags" surrounded by angle brackets within the web page content. It can embed scripts in languages such as JavaScript which affect the behavior of HTML webpages. HTML can also be used to include Cascading Style Sheets (CSS) to define the appearance and layout of text and other material. The W3C, maintainer of both HTML and CSS standards, encourages the use of CSS over explicit presentational markup.
XHTML is a separate language that began as a reformulation of HTML 4.01 using XML 1.0. It continues to be developed:
  • XHTML 1.0, published January 26, 2000 as a W3C Recommendation, later revised and republished August 1, 2002. It offers the same three variations as HTML 4.0 and 4.01, reformulated in XML, with minor restrictions.
  • XHTML 1.1,  published May 31, 2001 as a W3C Recommendation. It is based on XHTML 1.0 Strict, but includes minor changes, can be customized, is reformulated using modules from Modularization of XHTML, which was published April 10, 2001 as a W3C Recommendation.
  • XHTML 2.0. There is no XHTML 2.0 standard. XHTML 2.0 is incompatible with XHTML 1.x and, therefore, would be more accurate to characterize as an XHTML-inspired new language than an update to XHTML 1.x.
  • XHTML 5, which is an update to XHTML 1.x, is being defined alongside HTML 5 in the HTML 5 draft.

Markup

HTML markup consists of several key components, including elements (and their attributes), character-based data types, character references and entity references. Another important component is the document type declaration, which specifies the Document Type Definition. As of HTML 5, no Document Type Definition will need to be specified and will only determine the layout mode.
The Hello world program, a common computer program employed for comparing programming languages, scripting languages and markup languages is made of 9 lines of code in HTML, albeit Newlines are optional:
<html>
  <head>
    <title>Hello HTML</title>
  </head>
  <body>
    <p>Hello World!</p>
  </body>
</html>
This Document Type Declaration is for HTML 5.
If the declaration is not included, most browsers will render using "quirks mode".
HTML documents are composed entirely of HTML elements that, in their most general form have three components: a pair of element tags with a "start tag" and "end tag"; some element attributes given to the element within the tags; and finally, all the actual textual and graphical formation content that will be rendered on the display. An HTML element is everything between and including the tags. A tag is a keyword enclosed in angle brackets.
A common form of an HTML element is:
content to be rendered
The name of the HTML element is also the name of the tag. Note that the end tag's name starts with a slash character, "/".
The most general form of an HTML element is:
content to be rendered
By not assigning attributes most start tags default their attribute values.
There are some basic types of tags: Heading of the HTML:.... Usually the title should be included in the head, for example:
<head> 
<title>The title</title> 
</head>
Headings:
<h1>Heading1</h1>
<h2>Heading2</h2>
<h3>Heading3</h3>
<h4>Heading4</h4>
<h5>Heading5</h5>
<h6>Heading6</h6>
Paragraph Partition:
<p>Paragraph 1</p>  <p>Paragraph 2</p>
Newline:
. The difference between 
 and  is that 'br' breaks a line without altering the semantic structure of the page, whereas 'p' sections the page into paragraphs. Here is an example:
<code><p>This <br> is a paragraph <br> with <br> line breaks</p></code>
Annotation:
Annotations can help to understand the coding and do not display in the webpage.
There are several types of markup elements used in HTML.
  • Structural markup describes the purpose of text. For example,

    Golf

    establishes "Golf" as a second-level heading, which would be rendered in a browser in a manner similar to the "HTML markup" title at the start of this section. Structural markup does not denote any specific rendering, but most Web browsers have standardized default styles for element formatting. Text may be further styled with Cascading Style Sheets (CSS).
  • Presentational markup describes the appearance of the text, regardless of its function. For example boldface indicates that visual output devices should render "boldface" in bold text, but gives no indication what devices which are unable to do this (such as aural devices that read the text aloud) should do. In the case of both bold and italic, there are elements which usually have an equivalent visual rendering but are more semantic in nature, namely strong emphasis and emphasis respectively. It is easier to see how an aural user agent should interpret the latter two elements. However, they are not equivalent to their presentational counterparts: it would be undesirable for a screen-reader to emphasize the name of a book, for instance, but on a screen such a name would be italicized. Most presentational markup elements have become deprecated under the HTML 4.0 specification, in favor of CSS based style design.
  • Hypertext markup makes parts of a document into links to other documents. HTML up through version XHTML 1.1 requires the use of an anchor element to create a hyperlink in the flow of text: Wikipedia. In addition, the href attribute must be set to a valid URL. For example, the HTML markup, Wikipedia, will render the word "Wikipedia" as a hyperlink. An example to render an image as a hyperlink is: alternative text.
Most of the attributes of an element are name-value pairs, separated by "=" and written within the start tag of an element after the element's name. The value may be enclosed in single or double quotes, although values consisting of certain characters can be left unquoted in HTML (but not XHTML). Leaving attribute values unquoted is considered unsafe. In contrast with name-value pair attributes, there are some attributes that affect the element simply by their presence in the start tag of the element (like the ismap attribute for the img element).
Most elements can take any of several common attributes:
  • The id attribute provides a document-wide unique identifier for an element. This can be used by stylesheets to provide presentational properties: by browsers that focus attention on the specific element, or by scripts to alter the contents or presentation of an element. Appended to the URL of the page, it provides a globally unique identifier for an element, typically a sub-section of the page. For example, the ID "Attributes" in http://en.wikipedia.org/wiki/HTML#Attributes
  • The class attribute provides a way of classifying similar elements. This can be used for semantic or presentation purposes. Semantically, for example, classes are used in microformats. Presentationally, for example, an HTML document might use the designation class="notation" to indicate that all elements with this class value are subordinate to the main text of the document. Such elements might be gathered together and presented as footnotes on a page instead of appearing in the place where they occur in the HTML source.
  • An author may use the style non-attributal codes presentational properties to a particular element. It is considered better practice to use an element’s id or class attributes to select the element with a stylesheet, though sometimes this can be too cumbersome for a simple and specific or ad hoc application of styled properties.
  • The title attribute is used to attach subtextual explanation to an element. In most browsers this attribute is displayed as what is often referred to as a tooltip.
The abbreviation element, abbr, can be used to demonstrate these various attributes:
<abbr id="anId" class="aClass" style="color:blue;" title="Hypertext Markup Language">HTML</abbr>
This example displays as HTML; in most browsers, pointing the cursor at the abbreviation should display the title text "Hypertext Markup Language."
Most elements also take the language-related attributes lang and dir.
As of version 4.0, HTML defines a set of 252 character entity references and a set of 1,114,050 numeric character references, both of which allow individual characters to be written via simple markup, rather than literally. A literal character and its markup counterpart are considered equivalent and are rendered identically.
The ability to "escape" characters in this way allows for the characters < and & (when written as < and &, respectively) to be interpreted as character data, rather than markup. For example, a literal < normally indicates the start of a tag, and & normally indicates the start of a character entity reference or numeric character reference; writing it as & or & or & allows & to be included in the content of elements or the values of attributes. The double-quote character ("), when used to quote an attribute value, must also be escaped as " or " or " when it appears within the attribute value itself. The single-quote character ('), when used to quote an attribute value, must also be escaped as ' or ' (should NOT be escaped as ' except in XHTML documents.) when it appears within the attribute value itself. However, since document authors often overlook the need to escape these characters, browsers tend to be very forgiving, treating them as markup only when subsequent text appears to confirm that intent.
Escaping also allows for characters that are not easily typed or that aren't even available in the document's character encoding to be represented within the element and attribute content. For example, the acute-accented e (é), a character typically found only on Western European keyboards, can be written in any HTML document as the entity reference é or as the numeric references é or é. The characters comprising those references (that is, the &, the ;, the letters in eacute, and so on) are available on all keyboards and are supported in all character encodings, whereas the literal é is not.
HTML defines several data types for element content, such as script data and stylesheet data, and a plethora of types for attribute values, including IDs, names, URIs, numbers, units of length, languages, media descriptors, colors, character encodings, dates and times, and so on. All of these data types are specializations of character data.
HTML documents are required to start with a Document Type Declaration (informally, a "doctype"). In browsers, the function of the doctype is to indicate the rendering mode—particularly to avoid quirks mode.
The original purpose of the doctype was to enable parsing and validation of HTML documents by SGML tools based on the Document Type Definition (DTD). The DTD to which the DOCTYPE refers contains machine-readable grammar specifying the permitted and prohibited content for a document conforming to such a DTD. Browsers, on the other hand, do not implement HTML as an application of SGML and by consequence do not read the DTD. HTML 5 does not define a DTD, because of the technology's inherent limitations, so in HTML 5 the doctype declaration, , does not refer to a DTD.
An example of an HTML 4 doctype is
This declaration references the DTD for the Strict version of HTML 4.01, which does not include presentational elements like font, leaving formatting to Cascading Style Sheets and the span and div element. SGML-based validators read the DTD in order to properly parse the document and to perform validation. In modern browsers, this doctype activates standards mode as opposed to quirks mode.
In addition, HTML 4.01 provides Transitional and Frameset DTDs, as explained below.

Semantic HTML

Semantic HTML is a way of writing HTML that emphasizes the meaning of the encoded information over its presentation (look). HTML has included semantic markup from its inception, but has also included presentational markup such as , and
tags. There are also the semantically neutral span and div tags. Since the late 1990s when Cascading Style Sheets were beginning to work in most browsers, web authors have been encouraged to avoid the use of presentational HTML markup with a view to the separation of presentation and content.[
In a 2001 discussion of the Semantic Web, Tim Berners-Lee and others gave examples of ways in which intelligent software 'agents' may one day automatically trawl the Web and find, filter and correlate previously unrelated, published facts for the benefit of human users.  Such agents are not commonplace even now, but some of the ideas of Web 2.0, mashups and price comparison websites may be coming close. The main difference between these web application hybrids and Berners-Lee's semantic agents lies in the fact that the current aggregation and hybridisation of information is usually designed in by web developers, who already know the web locations and the API semantics of the specific data they wish to mash, compare and combine.
An important type of web agent that does trawl and read web pages automatically, without prior knowledge of what it might find, is the Web crawler or search-engine spider. These software agents are dependent on the semantic clarity of web pages they find as they use various techniques and algorithms to read and index millions of web pages a day and provide web users with search facilities without which the World Wide Web would be only a fraction of its current usefulness.
In order for search-engine spiders to be able to rate the significance of pieces of text they find in HTML documents, and also for those creating mashups and other hybrids as well as for more automated agents as they are developed, the semantic structures that exist in HTML need to be widely and uniformly applied to bring out the meaning of published text. Presentational markup tags are deprecated in current HTML and XHTML recommendations and are illegal in HTML 5.
Good semantic HTML also improves the accessibility of web documents (see also Web Content Accessibility Guidelines). For example, when a screen reader or audio browser can correctly ascertain the structure of a document, it will not waste the visually impaired user's time by reading out repeated or irrelevant information when it has been marked up correctly.

Delivery

HTML documents can be delivered by the same means as any other computer file. However, they are most often delivered either by HTTP from a Web server or by e-mail.

[edit] HTTP

The World Wide Web is composed primarily of HTML documents transmitted from Web servers to Web browsers using the Hypertext Transfer Protocol (HTTP). However, HTTP is used to serve images, sound, and other content, in addition to HTML. To allow the Web browser to know how to handle each document it receives, other information is transmitted along with the document. This meta data usually includes the MIME type (e.g. text/html or application/xhtml+xml) and the character encoding (see Character encoding in HTML).
In modern browsers, the MIME type that is sent with the HTML document may affect how the document is initially interpreted. A document sent with the XHTML MIME type is expected to be well-formed XML; syntax errors may cause the browser to fail to render it. The same document sent with the HTML MIME type might be displayed successfully, since some browsers are more lenient with HTML.
The W3C recommendations state that XHTML 1.0 documents that follow guidelines set forth in the recommendation's Appendix C may be labeled with either MIME Type. The current XHTML 1.1 Working Draft also states that XHTML 1.1 documents should be labeled with either MIME type.
Most graphical e-mail clients allow the use of a subset of HTML (often ill-defined) to provide formatting and semantic markup not available with plain text. This may include typographic information like coloured headings, emphasized and quoted text, inline images and diagrams. Many such clients include both a GUI editor for composing HTML e-mail messages and a rendering engine for displaying them. Use of HTML in e-mail is controversial because of compatibility issues, because it can help disguise phishing attacks, because it can confuse spam filters and because the message size is larger than plain text.
The most common filename extension for files containing HTML is .html. A common abbreviation of this is .htm, which originated because some early operating systems and file systems, such as DOS and FAT, limited file extensions to three letters.
An HTML Application (HTA; file extension ".hta") is a Microsoft Windows application that uses HTML and Dynamic HTML in a browser to provide the application's graphical interface. A regular HTML file is confined to the security model of the web browser, communicating only to web servers and manipulating only webpage objects and site cookies. An HTA runs as a fully trusted application and therefore has more privileges, like creation/editing/removal of files and Windows Registry entries. Because they operate outside the browser's security model, HTAs cannot be executed via HTTP, but must be downloaded (just like an EXE file) and executed from local file system.

Current variations

HTML is precisely what we were trying to PREVENT— ever-breaking links, links going outward only, quotes you can't follow to their origins, no version management, no rights management.
Since its inception, HTML and its associated protocols gained acceptance relatively quickly. However, no clear standards existed in the early years of the language. Though its creators originally conceived of HTML as a semantic language devoid of presentation details, practical uses pushed many presentational elements and attributes into the language, driven largely by the various browser vendors. The latest standards surrounding HTML reflect efforts to overcome the sometimes chaotic development of the language and to create a rational foundation for building both meaningful and well-presented documents. To return HTML to its role as a semantic language, the W3C has developed style languages such as CSS and XSL to shoulder the burden of presentation. In conjunction, the HTML specification has slowly reined in the presentational elements.
There are two axes differentiating various variations of HTML as currently specified: SGML-based HTML versus XML-based HTML (referred to as XHTML) on one axis, and strict versus transitional (loose) versus frameset on the other axis.

 

One difference in the latest HTML specifications lies in the distinction between the SGML-based specification and the XML-based specification. The XML-based specification is usually called XHTML to distinguish it clearly from the more traditional definition. However, the root element name continues to be 'html' even in the XHTML-specified HTML. The W3C intended XHTML 1.0 to be identical to HTML 4.01 except where limitations of XML over the more complex SGML require workarounds. Because XHTML and HTML are closely related, they are sometimes documented in parallel. In such circumstances, some authors conflate the two names as (X)HTML or X(HTML).
Like HTML 4.01, XHTML 1.0 has three sub-specifications: strict, loose and frameset.
Aside from the different opening declarations for a document, the differences between an HTML 4.01 and XHTML 1.0 document—in each of the corresponding DTDs—are largely syntactic. The underlying syntax of HTML allows many shortcuts that XHTML does not, such as elements with optional opening or closing tags, and even EMPTY elements which must not have an end tag. By contrast, XHTML requires all elements to have an opening tag and a closing tag. XHTML, however, also introduces a new shortcut: an XHTML tag may be opened and closed within the same tag, by including a slash before the end of the tag like this:
. The introduction of this shorthand, which is not used in the SGML declaration for HTML 4.01, may confuse earlier software unfamiliar with this new convention. A fix for this is to include a space before closing the tag, as such:
.
To understand the subtle differences between HTML and XHTML, consider the transformation of a valid and well-formed XHTML 1.0 document that adheres to Appendix C (see below) into a valid HTML 4.01 document. To make this translation requires the following steps:
  1. The language for an element should be specified with a lang attribute rather than the XHTML xml:lang attribute. XHTML uses XML's built in language-defining functionality attribute.
  2. Remove the XML namespace (xmlns=URI). HTML has no facilities for namespaces.
  3. Change the document type declaration from XHTML 1.0 to HTML 4.01. (see DTD section for further explanation).
  4. If present, remove the XML declaration. (Typically this is: ).
  5. Ensure that the document’s MIME type is set to text/html. For both HTML and XHTML, this comes from the HTTP Content-Type header sent by the server.
  6. Change the XML empty-element syntax to an HTML style empty element (
    to
    ).
Those are the main changes necessary to translate a document from XHTML 1.0 to HTML 4.01. To translate from HTML to XHTML would also require the addition of any omitted opening or closing tags. Whether coding in HTML or XHTML it may just be best to always include the optional tags within an HTML document rather than remembering which tags can be omitted.
A well-formed XHTML document adheres to all the syntax requirements of XML. A valid document adheres to the content specification for XHTML, which describes the document structure.
The W3C recommends several conventions to ensure an easy migration between HTML and XHTML (see HTML Compatibility Guidelines). The following steps can be applied to XHTML 1.0 documents only:
  • Include both xml:lang and lang attributes on any elements assigning language.
  • Use the empty-element syntax only for elements specified as empty in HTML.
  • Include an extra space in empty-element tags: for example instead of
    .
  • Include explicit close tags for elements that permit content but are left empty (for example,
    , not
    ).
  • Omit the XML declaration.

By carefully following the W3C’s compatibility guidelines, a user agent should be able to interpret the document equally as HTML or XHTML. For documents that are XHTML 1.0 and have been made compatible in this way, the W3C permits them to be served either as HTML (with a text/html MIME type), or as XHTML (with an application/xhtml+xml or application/xml MIME type). When delivered as XHTML, browsers should use an XML parser, which adheres strictly to the XML specifications for parsing the document's contents.
HTML 4 defined three different versions of the language: Strict, Transitional (once called Loose) and Frameset. The Strict version is intended for new documents and is considered best practice, while the Transitional and Frameset versions were developed to make it easier to transition documents that conformed to older HTML specification or didn't conform to any specification to a version of HTML 4. The Transitional and Frameset versions allow for presentational markup, which is omitted in the Strict version. Instead, cascading style sheets are encouraged to improve the presentation of HTML documents.
Because XHTML 1 only defines an XML syntax for the language defined by HTML 4, the same differences apply to XHTML 1 as well.
The Transitional version allows the following parts of the vocabulary, which are not included in the Strict version:
  • A looser content model
    • Inline elements and plain text are allowed directly in: body, blockquote, form, noscript and noframes
  • Presentation related elements
    • underline (u)
    • strike-through (s)
    • center
    • font
    • basefont
  • Presentation related attributes
    • background and bgcolor attributes for body element.
    • align attribute on div, form, paragraph (p) and heading (h1...h6) elements
    • align, noshade, size and width attributes on hr element
    • align, border, vspace and hspace attributes on img and object elements
    • align attribute on legend and caption elements
    • align and bgcolor on table element
    • nowrap, bgcolor, width, height on td and th elements
    • bgcolor attribute on tr element
    • clear attribute on br element
    • compact attribute on dl, dir and menu elements
    • type, compact and start attributes on ol and ul elements
    • type and value attributes on li element
    • width attribute on pre element
  • Additional elements in Transitional specification
    • menu list (no substitute, though unordered list is recommended)
    • dir list (no substitute, though unordered list is recommended)
    • isindex (element requires server-side support and is typically added to documents server-side, form and input elements can be used as a substitute)
    • applet (deprecated in favor of object element)
  • The language attribute on script element (redundant with the type attribute).
  • Frame related entities
    • iframe
    • noframes
    • target attribute on anchor, client-side image-map (imagemap), link, form and base elements
The Frameset version includes everything in the Transitional version, as well as the frameset element (used instead of body) and the frame element.
In addition to the above transitional differences, the frameset specifications (whether XHTML 1.0 or HTML 4.01) specifies a different content model, with frameset replacing body, that contains either frame elements, or optionally noframes with a body.
As this list demonstrates, the loose versions of the specification are maintained for legacy support. However, contrary to popular misconceptions, the move to XHTML does not imply a removal of this legacy support. Rather the X in XML stands for extensible and the W3C is modularizing the entire specification and opening it up to independent extensions. The primary achievement in the move from XHTML 1.0 to XHTML 1.1 is the modularization of the entire specification. The strict version of HTML is deployed in XHTML 1.1 through a set of modular extensions to the base XHTML 1.1 specification. Likewise, someone looking for the loose (transitional) or frameset specifications will find similar extended XHTML 1.1 support (much of it is contained in the legacy or frame modules). The modularization also allows for separate features to develop on their own timetable. So for example, XHTML 1.1 will allow quicker migration to emerging XML standards such as MathML (a presentational and semantic math language based on XML) and XForms—a new highly advanced web-form technology to replace the existing HTML forms.
In summary, the HTML 4.01 specification primarily reined in all the various HTML implementations into a single clearly written specification based on SGML. XHTML 1.0, ported this specification, as is, to the new XML defined specification. Next, XHTML 1.1 takes advantage of the extensible nature of XML and modularizes the whole specification. XHTML 2.0 will be the first step in adding new features to the specification in a standards-body-based approach.

Hypertext features not in HTML

HTML lacks some of the features found in earlier hypertext systems, such as typed links, source tracking, fat links and others.  Even some hypertext features that were in early versions of HTML have been ignored by most popular web browsers until recently, such as the link element and in-browser Web page editing.
Sometimes Web services or browser manufacturers remedy these shortcomings. For instance, wikis and content management systems allow surfers to edit the Web pages they visit.


jQuery
jQuery is a cross-browser JavaScript library designed to simplify the client-side scripting of HTML.
jQuery is free, open source software, dual-licensed under the MIT License and the GNU General Public License, Version 2. jQuery's syntax is designed to make it easier to navigate a document, select DOM elements, create animations, handle events, and develop Ajax applications. jQuery also provides capabilities for developers to create plugins on top of the JavaScript library. Using these facilities, developers are able to create abstractions for low-level interaction and animation, advanced effects and high-level, theme-able widgets. This contributes to the creation of powerful and dynamic web pages.
Features
jQuery contains the following features:
  • DOM element selections using the cross-browser open source selector engine Sizzle, a spin-off out of the jQuery project
  • DOM traversal and modification (including support for CSS 1-3)
  • Events
  • CSS manipulation
  • Effects and animations
  • Ajax
  • Extensibility through plug-ins
  • Utilities - such as browser version and the each function.
  • Cross-browser support
Use
The jQuery library is usually a single JavaScript file, containing all its common DOM, event, effects, and Ajax functions. It can be included within a web page using the following mark-up:
jQuery can also be loaded using the Google AJAX Libraries API with the following mark-up:
or (HTTPS and HTTP):
Microsoft hosts jQuery on its AJAX CDN (Content delivery network) making it easy to add the support for jQuery library. CDN serves JavaScript libraries from one of thousands of geo-located Microsoft edge-cache servers around the world.
jQuery has two usage styles:
  • via the $ function, which is a factory method for the jQuery object. These functions, often called commands, are chainable; they each return a jQuery object
  • via $.-prefixed functions. These are utility functions which do not work on the jQuery object per se.
Typically, access to and manipulation of multiple DOM nodes begins with the $ function being called with a CSS selector string, which results in a jQuery object referencing matching elements in the HTML page. This node set can be manipulated by calling instance methods on the jQuery object, or on the nodes themselves. For example:
$("div.test").add("p.quote").addClass("blue").slideDown("slow");
This line finds the union of all div tags with class attribute test and all p tags with CSS class attribute quote, adds the class attribute blue to each matched element, and then slides them down with an animation. The $ and add functions affect the matched set, while the addClass and slideDown affect the referenced nodes.
The methods prefixed with $. are convenience methods or affect global properties and behaviour. For example, the following is an example of the map function called each in jQuery:
$.each([1,2,3], function()
{
  document.write(this + 1);
});
This writes the number 234 to the document.
It is possible to perform browser-independent Ajax queries using $.ajax and associated methods to load and manipulate remote data.
$.ajax({
  type: "POST",
  url: "some.php",
  data: "name=John&location=Boston",
  success: function(msg){
    alert( "Data Saved: " + msg );
  }
});
This example posts the data name=John and location=Boston to some.php on the server. When this request finishes successfully, the success function is called to alert the user.
jQuery Plug-ins
Because jQuery is an open source construct, others are inclined to use its syntax to create plug-in code to further enable its functionality.
How jQuery WorksFrom jQuery JavaScript Library
Jump to: navigation, search
jQuery: The Basics
This is a basic tutorial, designed to help you get started using jQuery. If you don't have a test page setup yet, start by creating a new HTML page with the following contents:

 
   

   
 
 
    jQuery
 
Edit the src attribute in the script tag to point to your copy of jquery.js. For example, if jquery.js is in the same directory as your HTML file, you can use:

You can download your own copy of jQuery from the Downloading jQuery page
Launching Code on Document Ready
The first thing that most Javascript programmers end up doing is adding some code to their program, similar to this:
 window.onload = function(){ alert("welcome"); }
Inside of which is the code that you want to run right when the page is loaded. Problematically, however, the Javascript code isn't run until all images are finished downloading (this includes banner ads). The reason for using window.onload in the first place is that the HTML 'document' isn't finished loading yet, when you first try to run your code.
To circumvent both problems, jQuery has a simple statement that checks the document and waits until it's ready to be manipulated, known as the ready event:
 $(document).ready(function(){
   // Your code here
 });
Inside the ready event, add a click handler to the link:
 $(document).ready(function(){
   $("a").click(function(event){
     alert("Thanks for visiting!");
   });
 });
Save your HTML file and reload the test page in your browser. Clicking the link on the page should make a browser's alert pop-up, before leaving to go to the main jQuery page.
For click and most other events, you can prevent the default behaviour - here, following the link to jquery.com - by calling event.preventDefault() in the event handler:
 $(document).ready(function(){
   $("a").click(function(event){
     alert("As you can see, the link no longer took you to jquery.com");
     event.preventDefault();
   });
 });
Complete Example
The following is an example of what the complete HTML file might look like if you were to use the script in your own file. Note that it links to Google's CDN to load the jQuery core file. Also, while the custom script is included in the , it is generally preferable to place it in a separate file and refer that file with the script element's src attribute



  
  
  


   http://jquery.com/">jQuery


Adding and Removing an HTML Class
Important: The remaining jQuery examples will need to be placed inside the ready event so that they are executed when the document is ready to be worked on. See Launching Code on Document Ready above for details.
Another common task is adding (or removing) a class.
First, add some style information into the of your document, like this:

Next, add the addClass call to your script:
  $("a").addClass("test");
All your a elements will now be bold.
To remove the class, use removeClass
 $("a").removeClass("test");
*                                             (HTML allows multiple classes to be added to an element.)
Special Effects
In jQuery, a couple of handy effects are provided, to really make your web site stand out. To put this to the test, change the click that you added earlier to this:
 $("a").click(function(event){
   event.preventDefault();
   $(this).hide("slow");
 });
Now, if you click any link, it should make itself slowly disappear.
Callback and Functions
A callback is a function that is passed as an argument to another function and is executed after its parent function has completed. The special thing about a callback is that functions that appear after the "parent" can execute before the callback executes. Another important thing to know is how to properly pass the callback. This is where I have often forgotten the proper syntax.
Callback without arguments
For a callback with no arguments you pass it like this:
 $.get('myhtmlpage.html', myCallBack);
Note that the second parameter here is simply the function name (but not as a string and without parentheses). Functions in Javascript are 'First class citizens' and so can be passed around like variable references and executed at a later time.
Callback with arguments
"What do you do if you have arguments that you want to pass?", you might ask yourself.
Wrong
The Wrong Way (will not work!)
 $.get('myhtmlpage.html', myCallBack(param1, param2));

This will not work because it calls
myCallBack(param1, param2)
and then passes the return value as the second parameter to $.get()
Right
The problem with the above example is that myCallBack(param1, param2) is evaluated before being passed as a function. Javascript and by extension jQuery expects a function pointer in cases like these. I.E. setTimeout function.
In the below usage, an anonymous function is created (just a block of statements) and is registered as the callback function. Note the use of 'function(){'. The anonymous function does exactly one thing: calls myCallBack, with the values of param1 and param2 in the outer scope.
$.get('myhtmlpage.html', function(){
  myCallBack(param1, param2);
});
param1 and param2 are evaluated as a callback when the '$.get' is done getting the page.


This article discusses client-side validation using jQuery's validation plugin. That is, we will use JavaScript to validate the fields before submitting the form to the server. This is fast and efficient and provides quick replies to your visitor in the event of any errors. However, it is advisable to also validate the data on the server-side before adding it into the database.
A Simple Form
Let us start with a simple example. Our demonstration form contains four fields: name, e-mail, comment and URL. As you can see, the first three fields are required, whereas the URL field is optional. If you submit the form without filling in the required fields, you will be prompted with an error message.
Here is the code we used for the form in the demonstration above.

 
 
 
 

 

 
 

 
   

     
Name *

     
E-Mail *

     
URL

     
Your comment *

     

   

 
The code is quite straightforward and doesn't need much explanation. However, there are a few important points that I would like to bring to your attention.
·         Remember to include the the jQuery library and the bassistance validation plugin. The link to the jQuery library must come first in the head section, otherwise the validation will not work.
·         Remember to assign the id attribute of the form and the name attribute of all the fields that you want to validate.
Now, let us see the validate() function in detail.
$(document).ready(function() {
  $("#form1").validate({
    rules: {
      name: "required",    // simple rule, converted to {required: true}
      email: {             // compound rule
      required: true,
      email: true
      },
      url: {
        url: true
      },
      comment: {
        required: true
      }
    },
    messages: {
      comment: "Please enter a comment."
    }
  });
});
All we are doing here is initializing the validation of the form using the validate() function. It can take several parameters.
The two parameters we used are:
·         rules: allows you to specify which fields you want to validate. In this case, we are validating name, email, url and comment. For each field, we specify if the field is required (required: true). We can specify that it must be a valid e-mail address, URL, etc.
·         messages: allows you to specify the error message for a particular field (like the comments field in the example above). If you don't specify it, a default message is provided that says "this field is required".
In the example above, we only used three validation methods (required, email and url). There are several other methods that can be used here. Here are a few of them:
·         remote: requests a resource to check the element for validity.
·         min: makes the element require a given minimum.
·         date: makes the element require a date.
·         creditcard: makes the element require a credit card number.
·         equalTo: requires the element to be the same as another one.
You can find an exhaustive list of built-in validation methods at http://docs.jquery.com/Plugins/Validation.
Bottom of Form
As there is no built-in method to validate a drop down menu, we need to define our own method.

jQuery.validator.addMethod(
  "selectNone",
  function(value, element) {
    if (element.value == "none")
    {
      return false;
    }
    else return true;
  },
  "Please select an option."
);

$(document).ready(function() {
  $("#form2").validate({
    rules: {
      sport: {
        selectNone: true
      }
    },
  });
})
We do so by calling the jQuery.validator.addMethod() method. It takes three parameters:
·         name: The name of the method, used to identify and referencing it, must be a valid javascript identifier.
·         method: the actual method implementation, returning true if an element is valid.
·         message: The default message to display for this method.
In the validate function, we specify that the 'sport' field should be validated using the selectNone method.
Being able to define your own validation methods allows you to validate pretty much anything that you can think of. Using this plugin, you can very quickly add validation to a form. However, let me remind you that this validation happens only on the client side. While JavaScript validation is useful because of its responsiveness, if there is a JavaScript error, the browser could ignore the remaining validation and submit the form to the server. So my final word of advice would be to validate the data again on the server side.
Some more additional methods, which I wrote are—

$.validator.addMethod("minchar", function(value, element, params) {
                return this.optional(element) || value.length >= params;
}, "");

$.validator.addMethod("matchValue", function(value, element, params) {
                return this.optional(element) || !value.match(params);
}, "");


$.validator.addMethod("date",function(value, element) {
            var check = false;
            var re = /^\d{1,2}\/\d{1,2}\/\d{4}$/
            if( re.test(value)){
                  var adata = value.split('/');
                  var mm = parseInt(adata[0],10);
                  var gg = parseInt(adata[1],10);
                  var aaaa = parseInt(adata[2],10);
                  var xdata = new Date(aaaa,mm-1,gg);
                  if ( ( xdata.getFullYear() == aaaa ) && ( xdata.getMonth () == mm - 1 ) && ( xdata.getDate() == gg ) )
                        check = true;
                  else
                        check = false;
            } else
                  check = false;
            return this.optional(element) || check;
      },
      ""
);

$.validator.addMethod("dateOfBirth", function(value,element) {
            return this.optional(element) || new Date($("#dob").val()) <= new Date();
      }, ""
);

$.validator.addMethod("multipleCheck",function(value, element) {
      var check= true;
      $('input[name="cardNumber"]').each(function(index){
            if($(this).val()=="XXXX")
            {
                  check= false;
            }
      } );
      return this.optional(element) || check;
},"");

$.validator.addMethod("multipleRequired",function(value, element) {
      var check= true;
       $('input[name="cardNumber"]').each(function(index){
            if($(this).val()=="")
            {
                  check= false;
            }
      } );
      return this.optional(element) || check;
},"");


jQuery for it is—

$(document).ready(function() {
var v_addNewCardNoSavedAddress = $("#addNewCardNoSavedAddress").validate({
rules: {
                  cardType: { matchValue:'Select Card Type'},
      cardNumber: { required: true, multipleCheck:true, multipleRequired:true },
                  newPassword: { required: true,minchar: 8, password:true },
dob:{date:true, dateOfBirth:true }
                 
},
            messages: {
                  cardType: { matchValue:"Please enter Card Type." },
                  cardNumber: {
                        required: "Please enter Card Number",
                        multipleCheck:"Please enter Card Number.",
                        multipleRequired:"Please enter Card Number"},
                 
                        },
newPassword: {
                        required: "Please enter Password.",
                        minchar: "Password must be of minimum 8 characters.",
password: "Password must be of minimum 8 characters and maximum 40 characters with no spaces, with at least one upper case characater and one special character."

                        },
dob:{
                        date: "Please enter valid Date.",
      dateOfBirth: "Please enter a date that is not in future."
                  }

},
      errorClass: "errorField",
      errorElement: "span",
      errorPlacement:function(error, element) {
            error.appendTo( element.parent() );
      }

      });
     
     
     
     
     


No comments:

Post a Comment