All notes


An intro example:

<!DOCTYPE html>
<script src=""></script>
// Shorter version for $(document).ready(). See below for why using it:
		$(this).hide(); // Remember the ';' here.

<p>If you click on me, I will disappear.</p>
<p>Click me away!</p>
<p>Click me too!</p>


Why should always wrap js into document.ready event callback

w3schools. All jQuery methods should be inside a document ready event, to prevent any jQuery code from running before the document is finished loading (is ready).

// Shorter version.
   // jQuery methods go here...

   // jQuery methods go here...

Send a JSON object using html form data:

var formData = JSON.stringify($("#myForm").serializeArray());

  type: "POST",
  url: "serverUrl",
  data: formData,
  success: function(){},
  dataType: "json",
  contentType : "application/json"


The jQuery library contains the following features:

One big advantage of using the hosted jQuery from Google or Microsoft:
Many users already have downloaded jQuery from Google or Microsoft when visiting another site. As a result, it will be loaded from cache when they visit your site, which leads to faster loading time. Also, most CDN's will make sure that once a user requests a file from it, it will be served from the server closest to them, which also leads to faster loading time.


Language references

For loop

var obj = {
  name: "Pete",
  age: 15
// Method 1: vanillaJS
for( key in obj ) {
  alert( "key is " + [ key ] + ", value is " + obj[ key ] );
// Method 2: jQuery each
jQuery.each( obj, function( key, value ) {
  console.log( "key", key, "value", value );

var x = [ 1, 2, 3 ];
jQuery.each( x, function( index, value ) {
  console.log( "index", index, "value", value );


See reference for a full list.

$("*") 	Selects all elements
$(this) 	Selects the current HTML element
$("#lastname") 	The element with id="lastname"
$(".intro,.demo") 	All elements with the class "intro" or "demo"
$("p.intro") 	Selects all <p> elements with class="intro"
$("h1,div,p") 	All <h1>, <div> and <p> elements

$("div > p") 	All <p> elements that are a direct child of a <div> element
$("div p") 	All <p> elements that are descendants of a <div> element
$("div + p") 	The <p> element that are next to each <div> elements
$("div ~ p") 	All <p> elements that are siblings of a <div> element

Notice the difference below:
$("ul li:first") 	Selects the first <li> element of the first <ul>
$("ul li:first-child") 	Selects the first <li> element of every <ul>
$("p:first") 	The first <p> element
$("p:last") 	The last <p> element
$("tr:even") 	Selects all even <tr> elements
$("tr:odd") 	Selects all odd <tr> elements
$("p:first-child") 	All <p> elements that are the first child of their parent
$("p:nth-child(2)") 	All <p> elements that are the 2nd child of their parent
$("p:last-child") 	All <p> elements that are the last child of their parent
$("p:first-of-type") 	All <p> elements that are the first <p> element of their parent
$("p:nth-of-type(2)") 	All <p> elements that are the 2nd <p> element of their parent
$("p:nth-last-of-type(2)") 	All <p> elements that are the 2nd <p> element of their parent, counting from the last child
$("p:only-child") 	All <p> elements that are the only child of their parent
$("p:only-of-type") 	All <p> elements that are the only child, of its type, of their parent

$("[href]") 	Selects all elements with an href attribute
$("a[target='_blank']") 	Selects all <a> elements with a target attribute value equal to "_blank"
$("a[target!='_blank']") 	Selects all <a> elements with a target attribute value NOT equal to "_blank"
$("[href$='.jpg']") 	All elements with a href attribute value ending with ".jpg"
$("[title|='Tomorrow']") 	All elements with a title attribute value equal to 'Tomorrow', or starting with 'Tomorrow' followed by a hyphen
$("[title^='Tom']") 	All elements with a title attribute value starting with "Tom"
$("[title~='hello']") 	All elements with a title attribute value containing the specific word "hello"
$("[title*='hello']") 	All elements with a title attribute value containing the word "hello"

$("ul li:eq(3)") 	The fourth element in a list (index starts at 0)
$("ul li:gt(3)") 	List elements with an index greater than 3
$("ul li:lt(3)") 	List elements with an index less than 3

$(":header") 	All header elements <h1>, <h2> ...
$(":animated") 	All animated elements
$(":focus") 	The element that currently has focus
$(":contains('Hello')") 	All elements which contains the text "Hello"
$("div:has(p)") 	All <div> elements that have a <p> element
$(":empty") 	All elements that are empty
$(":parent") 	All elements that are a parent of another element
$("input:not(:empty)") 	All input elements that are not empty
$("table:visible") 	All visible tables

$(":input") 	All input elements
$(":text") 	All input elements with type="text"
$(":password") 	All input elements with type="password"
$(":radio") 	All input elements with type="radio"
$(":checkbox") 	All input elements with type="checkbox"
$(":submit") 	All input elements with type="submit"
$(":reset") 	All input elements with type="reset"
$(":button") 	All input elements with type="button"
$(":image") 	All input elements with type="image"
$(":file") 	All input elements with type="file"
$(":enabled") 	All enabled input elements
$(":disabled") 	All disabled input elements
$(":selected") 	All selected input elements
$(":checked") 	All checked input elements

Select elements with same ID

<div id="red">1</div>
<div id="green">2</div>
<div id="red">3</div>
<div id="green">4</div>
<div id="red">5</div>
<div id="green">6</div>

// Usuallly we use simple ‘#’ with id like this:
// Only make first div red and first div green and dont do anything with other elements.
$(function() {
 $('#red').css('background-color', 'red');
 $('#green').css('background-color', 'green');

// This works: all red id div to red and green id div to green color.
$(function() {
 $('[id="red"]').css('background-color', 'red');
 $('[id="green"]').css('background-color', 'green');


Some common DOM events:

// To assign a click event to all paragraphs on a page, you can do this:

// Define what should happen when the event fires:
  // action goes here!!

	$(this).css("background-color", "#cccccc");

// Attach multiple event handlers:
	mouseenter: function(){
		$(this).css("background-color", "lightgray");
	mouseleave: function(){
		$(this).css("background-color", "lightblue");
	click: function(){
		$(this).css("background-color", "yellow");


What if other JavaScript frameworks also use the $ sign as a shortcut?

// Use jQuery instead.
		jQuery("p").text("jQuery is still working!");

// Use an alias.
var jq = $.noConflict();
		jq("p").text("jQuery is still working!");

// '$' is still workable inside.
		$("p").text("jQuery is still working!");


jquery API: types.


// Appends <b>hello</b>:
$( "<b>hello</b>" ).appendTo( "body" );
// Appends <b>hello</b>:
$( "<b>hello</b>bye" ).appendTo( "body" );
// Syntax error, unrecognized expression: bye<b>hello</b>
$( "bye<b>hello</b>" ).appendTo( "body" );
// Appends bye<b>hello</b>:
$( $.parseHTML( "bye<b>hello</b>" ) ).appendTo( "body" );
// Appends <b>hello</b>wait<b>bye</b>:
$( "<b>hello</b>wait<b>bye</b>" ).appendTo( "body" );


parseInt( "123" ) = 123 // (implicit decimal)
parseInt( "010" ) = 8 // (implicit octal)
parseInt( "0xCAFE" ) = 51966 // (implicit hexadecimal)
parseInt( "010", 10 ) = 10 // (explicit decimal)
parseInt( "11", 2 ) = 3 // (explicit binary)
parseFloat( "10.10" ) = 10.1

// Note the use of parenthesis:
"" + 1 + 2; // "12"
"" + ( 1 + 2 ); // "3"
"" + 0.0000001; // "1e-7"
parseInt( 0.0000001 ); // 1 (!)

parseInt( "hello", 10 ) // NaN
1 / 0 // Infinity
typeof NaN // "number"
typeof Infinity // "number"
NaN === NaN // false (!)
// But:
Infinity === Infinity // true


var x = [ 0, 3, 1, 2 ];
x.reverse()      // x = [ 2, 1, 3, 0 ]
x.join(" – ")    // Output: "2 - 1 - 3 - 0"
x.pop()          // x = [ 2, 1, 3 ]
x.unshift( -1 )  // Output: 4. x = [ -1, 2, 1, 3 ]
x.shift()        // Output: -1. x = [ 2, 1, 3 ]
x.sort()         // x = [ 1, 2, 3 ]
x.splice( 1, 2 ) // Output: [ 2, 3 ]. x = [1]. // The splice(index, howmany, item1, ...) method adds/removes items to/from an array, and returns the removed item(s).



jqueryAPI. Encode a set of form elements as an array of names and values.

$( "form" ).submit(function( event ) {
  console.log( $( this ).serializeArray() );
  // Prevent the default event effect.

Convert form data to JavaScript object with jQuery

<form action="" method="post">
First Name:<input type="text" name="Fname" maxlength="12" size="12"/> <br/>
Last Name:<input type="text" name="Lname" maxlength="36" size="12"/> <br/>
Male:<input type="radio" name="gender" value="Male"/><br/>
Female:<input type="radio" name="gender" value="Female"/><br/>
Favorite Food:<br/>
Steak:<input type="checkbox" name="food[]" value="Steak"/><br/>
Pizza:<input type="checkbox" name="food[]" value="Pizza"/><br/>
Chicken:<input type="checkbox" name="food[]" value="Chicken"/><br/>
<textarea wrap="physical" cols="20" name="quote" rows="5">Enter your favorite quote!</textarea><br/>
Select a Level of Education:<br/>
<select name="education">
<option value="Jr.High">Jr.High</option>
<option value="HighSchool">HighSchool</option>
<option value="College">College</option></select><br/>
Select your favorite time of day:<br/>
<select size="3" name="TofD">
<option value="Morning">Morning</option>
<option value="Day">Day</option>
<option value="Night">Night</option></select>
<p><input type="submit" /></p>
<pre id="result">

$.fn.serializeObject = function()
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[] !== undefined) {
            if (!o[].push) {
                o[] = [o[]];
            o[].push(this.value || '');
        } else {
            o[] = this.value || '';
    return o;

$(function() {
    $('form').submit(function() {
        return false;

Get, Set

The callback function has two parameters: the index of the current element in the list of elements selected and the original (old) value.

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
attr() - get attribute values.

	alert("Text: " + $("#test").text());
	alert("HTML: " + $("#test").html());
	alert("Value: " + $("#test").val());

// Callback function for setting.
	$("#test1").text(function(i, origText){
		return "Old text: " + origText + " New text: Hello world!
		(index: " + i + ")";

	$("#test2").html(function(i, origText){
		return "Old html: " + origText + " New html: Hello world!
		(index: " + i + ")";


// Toggles between the fadeIn() and fadeOut() methods.
// Stop animations or effects before it is finished:


    var div = $("div");
    div.animate({left: '100px'}, "slow");
    div.animate({fontSize: '3em'}, "slow");

// Chainning.
$("#p1").css("color", "red").slideUp(2000).slideDown(2000);


Unlike shorthand animation methods such as .slideDown() and .fadeIn(), the .animate() method does not make hidden elements visible as part of the effect.

Note that the target value of the height property is 'toggle'. Since the image was visible before, the animation shrinks the height to 0 to hide it. A second click then reverses this transition.

<div id="clickme">
  Click here
<img id="book" src="book.png" alt="" width="100" height="123"
  style="position: relative; left: 10px;">

// To animate the opacity, left offset, and height of the image simultaneously:
$( "#clickme" ).click(function() {
  $( "#book" ).animate({
    opacity: 0.25,
    left: "+=50",
    height: "toggle"
  }, 5000, function() {
    // Animation complete.


$.ajax({name:value, name:value, ... })

AJAX = Asynchronous JavaScript and XML. Without jQuery, AJAX coding can be a bit tricky: different browsers have different syntax for AJAX implementation.


Loads data from a server and puts the returned data into the selected element.


// Loads the content of the element with id="p1":
$("#div1").load("demo_test.txt #p1");

// responseTxt - contains the resulting content if the call succeeds
// statusTxt - contains the status of the call
// xhr - contains the XMLHttpRequest object
	$("#div1").load("demo_test.txt", function(responseTxt, statusTxt, xhr){
		if(statusTxt == "success")
			alert("External content loaded successfully!");
		if(statusTxt == "error")
			alert("Error: " + xhr.status + ": " + xhr.statusText);

Get, Post


	$.get("demo_test.asp", function(data, status){
		alert("Data: " + data + "\nStatus: " + status);

		name: "Donald Duck",
		city: "Duckburg"
	function(data, status){
		alert("Data: " + data + "\nStatus: " + status);



  type: "GET",
  url: "index1.php",
  dataType: 'json',
  async: false,
  username: username,
  password: password,
  data: '{ "comment" }',
  success: function (){
    alert('Thanks for your comment!'); 

// Preemptive method:
  type: "GET",
  url: "index1.php",
  dataType: 'json',
  async: false,
  headers: {
    "Authorization": "Basic " + btoa(USERNAME + ":" + PASSWORD)
  data: '{ "comment" }',
  success: function (){
    alert('Thanks for your comment!'); 

Ajax success data shown as [object object]?

alert() prints the string representation of the arguments - hence if you pass an object, you'll get [object Object].
To inspect data, use console.log(data) better. StackOverflow.

	type: "GET",
	url: "https://"+window.document.location.hostname+":443/accounts/"+$("#username").val(),
	username: $("#username").val(),
	password: $("#password").val(),
	success: function(data, status, xhr){
		// The following will show [object object]:
		// $("#res").text(returnedData)
	dataType: "json",
	contentType : "application/json"

Prettify json output with javascript

JSFiddle. StackOverflow.

// Simplest version:
var jsonString = '{"some":"json"}';
var jsonPretty = JSON.stringify(JSON.parse(jsonString),null,2);

// Advanced version:
function syntaxHighlight(json) {
	if (typeof json != 'string') {
		 json = JSON.stringify(json, undefined, 2);
	json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
	return json.replace(/("(\u[a-zA-Z0-9]{4}|\[^u]|[^\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
		var cls = 'number';
		if (/^"/.test(match)) {
			if (/:$/.test(match)) {
				cls = 'key';
			} else {
				cls = 'string';
		} else if (/true|false/.test(match)) {
			cls = 'boolean';
		} else if (/null/.test(match)) {
			cls = 'null';
		return '<span class="' + cls + '">' + match + '</span>';


AJAX examples

Form submitting

SO: jquery ajax submitting form.

Submitting JSON

css-tricks provides a customized serializeObject function.

<form id="contactForm1" action="/your_url" method="post">

<script type="text/javascript">
    // Serialize form to json.
    $.fn.serializeObject = function()
       var o = {};
       var a = this.serializeArray();
       $.each(a, function() {
           if (o[]) {
               if (!o[].push) {
                   o[] = [o[]];
               o[].push(this.value || '');
           } else {
               o[] = this.value || '';
       return o;

    var frm = $('#contactForm1');
    frm.submit(function (ev) {
            type: frm.attr('method'),
            url: frm.attr('action'),
            data: JSON.stringify(frm.serializeObject()),
            success: function (data) {
            dataType: "json",
            contentType : "application/json"

        // Prevent the current page being directed to form action URL.

Instead of return false you should be using e.preventDefault() to allow further event propagation after your click handler is complete. Using e.preventDefault() will only stop the default action of the Submit button (e.g. to submit the form) but will allow any other events bound to that form to execute.

SO: post JSON with jquery.

When you pass an object, jQuery uses $.param to serialize the object into name-value pairs. If you pass the data as a string, it won't be serialized:

    type: 'POST',
    url: '/form/',
    // Without the surrounding quotes, you're passing an object, not a JSON string:
    // data: {"name":"jonas"},
    data: '{"name":"jonas"}',
    // or:
    // JSON.stringify ({name: 'jonas'}),
    success: function(data) { alert('data: ' + data); },
    contentType: "application/json",
    dataType: 'json'

Handle with XML


Response XML:

<?xml version="1.0" encoding="UTF-8"?>
<response status="ok">

  type: 'GET',
  url: "foo.aspx",
  data: {
    key: "value"
  dataType: "xml",
  success: function (xml){
    var clientid = $(xml).find('client_id').first().text();


Success callback never called when posting JSON

csdn: Jquery ajax json 不执行success的原因

Phenomenon: 如果指定了dataType为json,老是不执行success回调,而是执行了error回调函数。只有小于1.3版本的jQuery才能执行success回调。 API ajax:

The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} instead.

原来返回的是{success:true,id:1} 这种不规则的字符串,不是严格的json格式,改成{"success":true,"id":"1"} 就可以正常执行success回调了。

Good References 18 surprises from reading jquery's source code.