All notes
Jquery

Examples

An intro example:


<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
// Shorter version for $(document).ready(). See below for why using it:
$(function(){
	$("p").click(function(){
		$(this).hide(); // Remember the ';' here.
	});
});
</script>
</head>
<body>

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

</body>
</html>

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.
$(function(){
   // jQuery methods go here...
}); 

$(document).ready(function(){
   // jQuery methods go here...
}); 

Send a JSON object using html form data:


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

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

Intro

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.

zepto.js

zeptojs.com.

Zepto is a minimalist JavaScript library for modern browsers with a largely jQuery-compatible API. If you use jQuery, you already know how to use Zepto.

Basics

Language references

Elements

How to add html



// https://stackoverflow.com/questions/9760328/clearest-way-to-build-html-elements-in-jquery
this.$fixture = $([
  "<div>",
  "  <div class='js-alert-box'></div>",
  "  <form id='my-form-to-validate'>",
  "    <input id='login-username' name='login-username'>",
  "  </form>",
  "</div>"
].join("\n"));

For, each



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 );
});

Selectors

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

// Combined:
$('input:radio[name="postage"]')

Select elements with same ID

php-freelancer.in.


<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');
});

Radio buttons on change

stackOverflow: jquery if radio button is checked.



var appended = $('<div />').text("You're appendin'!");
appended.id = 'appended';

$('input:radio[name="postage"]').change(
  function() {
    // checks that the clicked radio button is the one of value 'Yes'
    // the value of the element is the one that's checked (as noted by @shef in comments)
    if ($(this).val() == 'Yes') {
      // appends the 'appended' element to the 'body' tag
      $(appended).appendTo('body');
    }
    else {
      // if it's the 'No' button removes the 'appended' element.
      $(appended).remove();
    }
  });

Events

Some common DOM events:



// To assign a click event to all paragraphs on a page, you can do this:
$("p").click();

// Define what should happen when the event fires:
$("p").click(function(){
  // action goes here!!
});

$("input").focus(function(){
	$(this).css("background-color", "#cccccc");
});

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

<input id='wcf' type=checkbox></input>
<div id="res"></div>
(function(){
$('input#wcf').change(function(){
  $('div#res').html($('input#wcf').prop('checked')?'true':'false');
});
})();

prop() doesnot trigger change event

SO.



// You need to use .change() or .trigger("change") after changing the property:
$('input[type="checkbox"][name="something"]').prop("checked", false).change();

noConflict

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


// Use jQuery instead.
$.noConflict();
jQuery(document).ready(function(){
	jQuery("button").click(function(){
		jQuery("p").text("jQuery is still working!");
	});
});

// Use an alias.
var jq = $.noConflict();
jq(document).ready(function(){
	jq("button").click(function(){
		jq("p").text("jQuery is still working!");
	});
});

// '$' is still workable inside.
$.noConflict();
jQuery(document).ready(function($){
	$("button").click(function(){
		$("p").text("jQuery is still working!");
	});
});

Datatypes

jquery API: types.

HTMLString


// 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" );

Numbers


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

Arrays


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).

Functions

Traversing

Filtering

.first(), .last()

Reduce the set of matched elements to the first/last in the set.

.has()

Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element.



$( "li" ).has( "ul" ).css( "background-color", "red" );
// The result of this call is a red background for a "li" which has a <ul> among its descendants.

.is()

Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.



$( "ul" ).click(function( event ) {
  var target = $( event.target );
  if ( target.is( "li" ) ) {
    target.css( "background-color", "red" );
  }
});

Tree traversal

.closest()

api.jquery.com/closest.

For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

.closest() begins with the current element, while .parents() begins with the parent element.

Events

Event Handler attachment

.on(), .off()

api.jquery.com: off. Remove an event handler.

.off( events [, selector ] [, handler ] )

events
Type: String
One or more space-separated event types and optional namespaces, or just namespaces, such as "click", "keydown.myPlugin", or ".myPlugin".


$( "#dataTable tbody tr" ).on( "click", function() {
  console.log( $( this ).text() );
});
Attaching click event to a JQuery object not yet added to the DOM

SO.



// You can replace body with any parent element that exists on dom ready.
$('body').on('click', '#my-button', function () {
  console.log("yeahhhh!!! but this doesn't work for me :(");
});
Custom event in jQuery that isn't bound to a DOM element?

SO.



// In YUI, this creates an event that is bound to a variable, not to a DOM element:
var myevent = new YAHOO.util.CustomEvent("mycustomevent");

// You can trigger custom global events like this in jQuery, These will trigger for any element:
jQuery.event.trigger('mycustomevent', [arg1, arg2, arg3]);
// You can bind your event to a global DOM object if you don't want to bind it to an individual page element:
$(document).bind('mycustomevent', function (e, arg1, arg2, arg3) { /* ... */ });

one()

api.jquery.com: one.

Attach a handler to an event for the elements. The handler is executed at most once per element per event type.

stackOverflow. one() function is automatically moved to off state after first instance of occurance. on() is identical to one() but it needs to be manually put to off state otherwise the number of instances has no limit.



var i = 1;
$('.one').one('click', function() {
  $(this).text('I am clickable only once: ' + i);
  i++;
});

var j = 1;
$('.multiple').on('click', function() {
  $(this).text('I was clicked ' + j + ' times');
  j++;
});

_data()

slavchoslavchev.com.

You might want to know what event handlers are attached to a certain element or an object. You can do that with the $._data() method.



var $btn = $('#some-button-id');
$btn.on('click', function() {
  console.log('click handler');
});
$btn.on('mouseover', function() {
  console.log('mouseover handler');
});

$._data($btn, "events");
// Outputs to console:
// Object {click: Array[1], mouseover: Array[1]}

// In older versions of jQuery (prior version 1.8) you can use the following:
$btn.data("events");
Notice that the new method is not public or at least not intended to be public, i.e. it has an underscore in it’s name. That means that it’s not advisable to use it in production code. But as I said before it may be useful for debugging purposes.

addClass(), removeClass()

api.jquery.com.



// Switch elements' classes from one to another
$( "p" ).removeClass( "myClass noClass" ).addClass( "yourClass" );

// As of jQuery 1.4, the .addClass() method's argument can receive a function.
$( "ul li" ).addClass(function( index ) {
  return "item-" + index; // E.g. add "item-0" to the first list item.
});

// Calling removeClass with no parameters will remove all of the item's classes.
$("#item").removeClass();
// If you didn't have jQuery, then this would be pretty much your only option:
document.getElementById('item').className = '';

change()



.change( handler );
.change( [eventData ], handler );
.change()
// This method is a shortcut for .on( "change", handler ) in the first two variations, and .trigger( "change" ) in the third.

//----------

// Add change() so that the change event is triggered!
// https://www.drupal.org/project/commerce_extra/issues/2539148
if (new_quantity >= 1) {
  $(selector).val(new_quantity).change();
}

children()

api.jquery.com: children.

The .children() method differs from .find() in that .children() only travels a single level down the DOM tree while .find() can traverse down multiple levels to select descendant elements (grandchildren, etc.) as well.

Note also that like most jQuery methods, .children() does not return text nodes; to get all children including text and comment nodes, use .contents().



$( "div" ).children( ".selected" ).css( "color", "blue" );

clone()

api.jquery.com: clone.

It performs a deep copy of the set of matched elements, meaning that it copies the matched elements as well as all of their descendant elements and text nodes.



$( ".hello" ).clone().appendTo( ".goodbye" );

// This would produce:
<div class="container">
  <div class="hello">Hello</div>
  <div class="goodbye">
    Goodbye
    <div class="hello">Hello</div>
  </div>
</div>

contents()



// First retrieves the contents of ".container" and then filters it for text nodes (nodtType == 3), which are wrapped in paragraph tags. The contents are again filtered, this time for <br /> elements, and these elements are removed.
$( ".container" )
  .contents()
    .filter(function() {
      return this.nodeType === 3;
    })
      .wrap( "<p></p>" )
      .end()
    .filter( "br" )
    .remove();

css()



// You can use .css() to remove css property as well, like this:
// Setting the value of a style property to an empty string removes that property from an element if it has already been directly applied:
$(".icha0").css("background-color","");
$(".icha0").css("opacity","");

data(), removeData()

api.jquery.com.

Store arbitrary data associated with the matched elements or return the value at the named data store for the first element in the set of matched elements.



// We can set several distinct values for a single element and retrieve them later:
$( "body" ).data( "foo", 52 );
$( "body" ).data( "bar", { myType: "test", count: 40 } );
$( "body" ).data( { baz: [ 1, 2, 3 ] } );
$( "body" ).data( "foo" ); // 52
$( "body" ).data(); // { foo: 52, bar: { myType: "test", count: 40 }, baz: [ 1, 2, 3 ] }
// Prior to jQuery 1.4.3 (starting in jQuery 1.4) the .data() method completely replaced all data, instead of just extending the data object.

$( "div" ).removeData( "test1" );
// Note that .removeData() will only remove data from jQuery's internal .data() cache, and any corresponding data- attributes on the element will not be removed. A later call to data() will therefore re-retrieve the value from the data- attribute. To prevent this, use .removeAttr() alongside .removeData() to remove the data- attribute as well.

data-* attributes

As of jQuery 1.4.3 HTML 5 data- attributes will be automatically pulled in to jQuery's data object. The treatment of attributes with embedded dashes was changed in jQuery 1.6 to conform to the W3C HTML5 specification.


<div data-role="page" data-last-value="43" data-hidden="true" data-options='{"name":"John"}'></div>


// All of the following jQuery code will work.
$( "div" ).data( "role" ) === "page";
$( "div" ).data( "lastValue" ) === 43;
$( "div" ).data( "hidden" ) === true;
$( "div" ).data( "options" ).name === "John";

//---------- attr() also works:

// https://stackoverflow.com/questions/7497066/is-it-possible-to-set-custom-attribute-by-jquery-attr-function-using-js-variab

// For
// <div data-test="lala">asdf</div>

alert($('div').data('test')); // lala
var t = 'data-test2';
var v = 'hiho';
$('div').attr(t,v);
alert($('div').data('test2')); // hiho
alert($('div').attr('data-test2')); // hiho

find()



$( "li.item-ii" ).find( "li" ).css( "background-color", "red" );

// If we need to retrieve all of the descendant elements, we can pass in the universal selector '*' to accomplish this.
$( "li.item-ii" ).find( "*" ).css( "background-color", "red" );
// $( "li.item-ii" ).find( "li" ) is equivalent to $( "li", "li.item-ii" ).

getScript()

api.jquery.com: getScript.

The script is executed in the global context, so it can refer to other variables and use jQuery functions. Included scripts can have some impact on the current page.



jQuery.getScript( url [, success ] );
// This is a shorthand Ajax function, which is equivalent to:
$.ajax({
  url: url,
  dataType: "script",
  success: success
});

get()

api.jquery.com: get.



console.log( $( "li" ).get( 0 ) );
// Same as:
console.log( $( "li" )[ 0 ] );


<div>One</div>
<div>Two</div>
<div>Three</div>
<script>
function display( divs ) {
  var a = [];
  for ( var i = 0; i < divs.length; i++ ) {
    a.push( divs[ i ].innerHTML );
  }
  $( "span" ).text( a.join(" ") );
}
display( $( "div" ).get().reverse() );
</script>

<!-- Output in HTML:
Reversed - Three Two One
One
Two
Three
-->

html(), text()



$('div#res').text($('input#wcf').prop('checked')); // When prop('checked') is false, it outputs "false."
$('div#res').html($('input#wcf').prop('checked')); // When prop('checked') is false, it outputs "" (nothing!)

jquery(), \$()

api.jquery.com.



jQuery( selector [, context ] )
jQuery( html [, ownerDocument ] )
jQuery( callback )

// The third format: Execute the function when the DOM is ready to be used.
$(function() {
  // Document is ready
});


// Define a plain object
var foo = { foo: "bar", hello: "world" };
 
// Pass it to the jQuery function
var $foo = $( foo );
 
// Test accessing property values
var test1 = $foo.prop( "foo" ); // bar
 
// Test setting property values
$foo.prop( "foo", "foobar" );
var test2 = $foo.prop( "foo" ); // foobar

// The use of .data() (or any method requiring .data()) on a plain object will result in a new property on the object called jQuery{randomNumber} (eg. jQuery123456789).
// Test using .data() as summarized above
$foo.data( "keyName", "someValue" );
console.log( $foo ); // will now contain a jQuery{randomNumber} property
 
// Test binding an event name and triggering
$foo.on( "eventName", function () {
  console.log( "eventName was called" );
});
 
$foo.trigger( "eventName" ); // Logs "eventName was called"

//----------
// Find all p elements that are children of a div element and apply a border to them.
$( "div > p" ).css( "border", "1px solid gray" );
// Find all inputs of type radio within the first form in the document.
$( "input:radio", document.forms[ 0 ] );

//---------- Create a new DOM element with HTML
$( "<p id='test'>My <em>new</em> text</p>" ).appendTo( "body" );

//---------- Create

$( "<div></div>", {
  // The name "class" must be quoted in the object since it is a JavaScript reserved word, and "className" cannot be used since it refers to the DOM property, not the attribute.
  "class": "my-div",
  on: {
    touchstart: function( event ) {
      // Do something
    }
  }
}).appendTo( "body" );

$( "<div></div>" )
  .addClass( "my-div" )
  .on({
    touchstart: function( event ) {
      // Do something
    }
  })
  .appendTo( "body" );

position()

Get the current coordinates of the first element in the set of matched elements, relative to the offset parent.

It retrieves the current position of an element (specifically its margin box) relative to the offset parent (specifically its padding box, which excludes margins and borders).

jquery.com: position.

serializeArray()

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.
  event.preventDefault();
});

Convert form data to JavaScript object with jQuery


  <h2>Form</h2>
<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/>
Gender:<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>
</form>
  <h2>JSON</h2>
<pre id="result">
</pre>

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

$(function() {
    $('form').submit(function() {
        $('#result').text(JSON.stringify($('form').serializeObject()));
        return false;
    });
});

checkbox



// https://stackoverflow.com/questions/901712/how-to-check-whether-a-checkbox-is-checked-in-jquery

//---------- Three methods
// jQuery 1.6+
$('#isAgeSelected').prop('checked')
// jQuery 1.5 and below
$('#isAgeSelected').attr('checked')
// Any version of jQuery
// Assuming an event handler on a checkbox
if (this.checked) {};

//---------- Using jQuery > 1.6
// traditional attr
$('#checkMeOut').attr('checked'); // "checked"
// new property method
$('#checkMeOut').prop('checked'); // true


if(document.getElementById('isAgeSelected').checked) {
  $("#txtAge").show();
} else {
  $("#txtAge").hide();
}

// Much prettier way to do the same:
$('#isAgeSelected').click(function() {
  $("#txtAge").toggle(this.checked);
});

// Or
$("#txtAge").toggle($("#isAgeSelected").is(':checked'));

//---------- Toggle Checkboxes on/off
var checkBoxes = $("input[name=recipients\\[\\]]");
checkBoxes.prop("checked", !checkBoxes.prop("checked"));

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.

$("#btn1").click(function(){
	alert("Text: " + $("#test").text());
});
$("#btn2").click(function(){
	alert("HTML: " + $("#test").html());
});
$("#btn1").click(function(){
	alert("Value: " + $("#test").val());
});

// Callback function for setting.
$("#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 world!
		(index: " + i + ")";
	});
});

Effects: hide/show, toggle, fade, slide, animate


$(selector).hide(speed,callback);
$(selector).show(speed,callback);
$(selector).toggle(speed,callback);
$(selector).fadeIn(speed,callback);
$(selector).fadeOut(speed,callback);
// Toggles between the fadeIn() and fadeOut() methods.
$(selector).fadeToggle(speed,callback);
$(selector).fadeTo(speed,opacity,callback);
$(selector).slideDown(speed,callback);
$(selector).slideUp(speed,callback);
$(selector).slideToggle(speed,callback);
$(selector).animate({params},speed,callback);
// Stop animations or effects before it is finished:
$(selector).stop(stopAll,goToEnd);

$("button").click(function(){
    $("#div1").fadeIn();
    $("#div2").fadeIn("slow");
    $("#div3").fadeIn(3000);
});

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

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

animate

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
</div>
<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.
  });
});

show/hide()

show() is roughly equivalent to calling .css( "display", "block" ), except that the display property is restored to whatever it was initially, e.g. "inline".

hide(): The matched elements will be hidden immediately, with no animation. This is roughly equivalent to calling .css( "display", "none" ), except that the value of the display property is saved in jQuery's data cache so that display can later be restored to its initial value.



$("#test").hide();
// Same as the JS:
document.getElementById("test").style.display = "none";
// But not like
document.getElementById("test").style.visibility = "hidden";

//---------- Check if hide or show

// Checks css for display:[none|block], ignores visibility:[true|false]
$(element).is(":visible"); 

// The same works with hidden
$(element).is(":hidden"); 

Does using display: none effectively remove the element from the DOM

Keep in mind that CSS is for style only, it does not have the ability to affect the DOM.

trigger(), on(), triggerHandler()

api.jquery.com: trigger.

To trigger handlers bound via jQuery without also triggering the native event, use .triggerHandler() instead.



//---------- Definitions.
.trigger( eventType [, extraParameters ] );
// eventType. Type: String. A string containing a JavaScript event type, such as click or submit.
.trigger( event [, extraParameters ] );
// event. Type: Event. A jQuery.Event object.

//---------- on, trigger.
$( "#foo" ).on( "click", function() {
  alert( $( this ).text() );
});
$( "#foo" ).trigger( "click" );

//---------- custom event type.
$( "#foo" ).on( "custom", function( event, param1, param2 ) {
  console.log(event); // jQuery.Event
  alert( param1 + "\n" + param2 );
});
$( "#foo").trigger( "custom", [ "Custom", "Event" ] );

//---------- event namespacing
// If you want to add a single event and then remove it (without removing any others that might have been added) then you can use event namespacing:
// https://stackoverflow.com/questions/209029/best-way-to-remove-an-event-handler-in-jquery
$('#myimage').on('click.mynamespace', function() { /* Do stuff */ });
$('#myimage').off('click.mynamespace');

prop(), attr()

api.jquery.com: prop.

.prop( propertyName )
.prop( propertyName, value )

prop vs attr

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.

The most important concept to remember about the "checked attribute" is that it does not correspond to the "checked property". The attribute actually corresponds to the "defaultChecked" property and should be used only to set the initial value of the checkbox. The checked attribute value does not change with the state of the checkbox, while the checked property does. api.jquery.com/attr.

"checked"

The "checked" attribute does not correspond to the "checked" property. The attribute actually corresponds to the "defaultChecked" property and should be used only to set the initial value of the checkbox. The checked attribute value does not change with the state of the checkbox, while the checked property does.



<input id="check1" type="checkbox" checked="checked">
<label for="check1">Check me</label>
<p></p>
 
<script>
$( "input" ).change(function() {
  var $input = $( this );
  $( "p" ).html(
    ".attr( \"checked\" ): <b>" + $input.attr( "checked" ) + "</b><br>" +
    ".prop( \"checked\" ): <b>" + $input.prop( "checked" ) + "</b><br>" +
    ".is( \":checked\" ): <b>" + $input.is( ":checked" ) + "</b>" );
}).change();

$("input").prop("checked", true);
</script>
<!-- $input.attr( "checked" ) will always be "checked". The other two will be true/false according to the checked status. -->

val()

Get the current value of the first element in the set of matched elements or set the value of every matched element.



// Get the value from a checked checkbox
$( "input[type=checkbox][name=bar]:checked" ).val();
 
// Get the value from a set of radio buttons
$( "input[type=radio][name=baz]:checked" ).val();

// Will make the value to upper case.
$( "input" ).on( "blur", function() {
  $( this ).val(function( i, val ) {
    return val.toUpperCase();
  });
});

//---------- Recommed to use prop() instead of val().
// Check #x
$( "#x" ).prop( "checked", true );
// Uncheck #x
$( "#x" ).prop( "checked", false );

Set select checked

val() allows you to pass **an array of element values**. This is useful when working on a jQuery object containing elements like <input type="checkbox">, <input type="radio">, and <option>s inside of a <select>. In this case, the inputs and the options having a value that matches one of the elements of the array will be checked or selected while those having a value that doesn't match one of the elements of the array will be unchecked or unselected, depending on the type. In the case of <input type="radio">s that are part of a radio group and <select>s, any previously selected element will be deselected.

Setting values using this method (or using the native value property) does not cause the dispatch of the change event. For this reason, the relevant event handlers will not be executed. If you want to execute them, you should call .trigger( "change" ) after setting the value.

SO.



<!-- ---------- Example from JQuery -->
<!-- http://api.jquery.com/val/#val2 -->
<select id="single">
  <option>Single</option>
  <option>Single2</option>
</select>
 
<select id="multiple" multiple="multiple">
  <option selected="selected">Multiple</option>
  <option>Multiple2</option>
  <option selected="selected">Multiple3</option>
</select>
 
<br>
<input type="checkbox" name="checkboxname" value="check1"> check1
<input type="checkbox" name="checkboxname" value="check2"> check2
<input type="radio" name="r" value="radio1"> radio1
<input type="radio" name="r" value="radio2"> radio2
 
<script>
$( "#single" ).val( "Single2" ); <!-- Here we set value on "select", but not "option". If we set values on "option", it will change the "value" attributes instead!!! -->
$( "#multiple" ).val([ "Multiple2", "Multiple3" ]);
$( "input").val([ "check1", "check2", "radio1" ]); <!-- Here we set value on "input". -->
</script>

<!-- ---------- Example: set value on inputs  -->

<input type="radio" name="test" checked value="a" />
<input type="radio" name="test" value="b" />
<script>
$(function() {
	$('[name="test"]').val(['a']); // Here you must give an array!
});
</script>

<!-- ---------- Example: set value on selects  -->

<div class="id_100">
  <select>
    <option value="val1">Val 1</option>
    <option value="val2">Val 2</option>
    <option value="val3">Val 3</option>
  </select>
</div>

<script>
$("div.id_100 select").val("val2"); // Here a value just works.
</script>

AJAX

w3shools.com.

$.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.

load

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


$(selector).load(URL,data,callback);

// 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
$("button").click(function(){
	$("#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);
	});
});

jquery.get(), jquery.post()


$.get(URL,callback);
$.post(URL,data,callback); 

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

$("button").click(function(){
	$.post("demo_test_post.asp",
	{
		name: "Donald Duck",
		city: "Duckburg"
	},
	function(data, status){
		alert("Data: " + data + "\nStatus: " + status);
	});
});

HTTP Auth

StackOverflow.


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

// Preemptive method:
$.ajax
({
  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.


$.ajax({
	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)
		console.log(data)
		alert(JSON.stringify(data))
	},
	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>';
	});
}

$("#res").html(syntaxHighlight(dataObject))

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">
    ...
</form>

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

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

        // Prevent the current page being directed to form action URL.
        ev.preventDefault();
    });
</script>

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:


$.ajax({
    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

SO.

Response XML:


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

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

AJAX FAQ

Success callback never called when posting JSON

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

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

jquery.com: 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回调了。

Deferred

api.jquery.com: jquery.deferred.

Why we need it

The usual ajax way:



$.ajax({
  url: "/echo/json/",
  data: {json: JSON.stringify({firstName: "Jose", lastName: "Romaniello"})} ,
  type: "POST",
  success: function(person){
    alert(person.firstName + " saved."); 
  },
  error: function(){ 
    alert("error!");
  }
});

This works but it is not an standard interface, it requires some work inside the post method and we can't register multiple callbacks.

Deferred()

A factory function that returns a chainable utility object (Deferred Object) with methods to register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function.

A Deferred object starts in the pending state. Any callbacks added to the object with deferred.then(), deferred.always(), deferred.done(), or deferred.fail() are queued to be executed later.

Calling deferred.resolve() or deferred.resolveWith() transitions the Deferred into the resolved state and immediately executes any doneCallbacks that are set. Calling deferred.reject() or deferred.rejectWith() transitions the Deferred into the rejected state and immediately executes any failCallbacks that are set.

Once the object has entered the resolved or rejected state, it stays in that state. Callbacks can still be added to the resolved or rejected Deferred — they will execute immediately.



var deferred = $.Deferred();
deferred.then(function(value) {
  alert(value);
  return 42;
}).then(function(id){
  alert('The answer : ' + id);
});

deferred.resolve("hello world");

// Will first alert "hello world", then alert "The answer : 42".

//----------

var loadPageViewLoaded = $.Deferred();
var loadPageEditorLoaded = $.Deferred();
asyncLoadPackage('layout_page_view').then(function(requiredModule) {
  loadPageViewLoaded.resolve(requiredModule);
});
asyncLoadPackage('layout_page_edit').then(function(requiredModule) {
  loadPageEditorLoaded.resolve(requiredModule);
});
$.when(loadPageViewLoaded, loadPageEditorLoaded).done(function(layoutPageView, layourPageEditor) {
  console.log(layoutPageView, layourPageEditor);
});

Promise()

This method returns an object with almost the same interface than the Deferred(), but it only have the methods to attach callbacks and does not have the methods to resolve and reject.

This is useful when you want to give to the calling API something to subscribe to, but not the ability to resolve or reject the deferred.

The ajax() method in JQuery returns a Promise, so you can do:



var post = $.ajax({
  url: "/echo/json/",
  data: {json: JSON.stringify({firstName: "Jose", lastName: "Romaniello"})} ,
  type: "POST"
});

post.done(function(p){
  alert(p.firstName +  " saved.");
});

post.fail(function(){
  alert("error!");
});

// You can add as many callbacks as you want.

pipe()

It allows you to “project” a promise.

Projection



function getCustomerSSNById(customerId){
  return $.post("/echo/json/", {
      json: JSON.stringify({firstName: "Jose", lastName: "Romaniello", ssn: "123456789"})
  }).pipe(function(p){
    return p.ssn; // Get a projection.
  });
}

function getPersonAddressBySSN(ssn){
  return $.post("/echo/json/", {
      json: JSON.stringify({
        ssn: "123456789",
        address: "Siempre Viva 12345, Springfield" })
  }).pipe(function(p){
    return p.address;
  });
}

function getPersonAddressById(id){
  return getCustomerSSNById(id)
       .pipe(getPersonAddressBySSN);  
}

getPersonAddressById(123)
  .done(function(a){
    alert("The address is " + a); 
  });

Recursive deferred

Imagine that you started an asynchronous operation in the backend, and you need to do “polling” to see if the task is done and when the task is done do something else.



//1: done, 2: cancelled, other: pending
function getPrintingStatus(){
  var d = $.Deferred();
  $.post(
    "/echo/json/",
    {
      json: JSON.stringify( {status: Math.floor(Math.random()*8+1)} ),
      delay: 2
    }
  ).done(function(s){
    d.resolve(s.status);
  }).fail(d.reject); 
  return d.promise();
}

function pollUntilDone(){
  //do something
  return getPrintingStatus()
      .pipe(function(s){
        if(s === 1 || s == 2) {
          return s;  //if the status is done or cancelled return the status
        }
        //if the status is pending... call this same function
        //and return a deferred...
        return pollUntilDone();
      });
}

$.blockUI({message: "Loading..."});

pollUntilDone()
  .pipe(function(s){ //project the status code to a meaningfull string.
      switch(s){
      case 1:
        return "done";
      case 2:
        return "cancelled";
      }  
  })
  .done(function(s){
    $.unblockUI();
    alert("The status is " + s);
  });

when()

The method accepts an arbitrary number of promises, and it returns a master deferred that:

The done callback has the results of all the promises.



function getCustomer(customerId){
  var d = $.Deferred();
  $.post(
    "/echo/json/",
    {json: JSON.stringify({firstName: "Jose", lastName: "Romaniello", ssn: "123456789"})}
  ).done(function(p){
    d.resolve(p);
  }).fail(d.reject); 
  return d.promise();
}

function getPersonAddressBySSN(ssn){
  return $.post("/echo/json/", {
      json: JSON.stringify({
        ssn: "123456789",
        address: "Siempre Viva 12345, Springfield" })
  }).pipe(function(p){
    return p.address;
  });
}

$.when(getCustomer(123), getPersonAddressBySSN("123456789"))
  .done(function(person, address){
    alert("The name is " + person.firstName + " and the address is " + address);
  });

Good References

quickLeft.com: 18 surprises from reading jquery's source code.