02.06.2013 Views

Pro PHP and jQuery by Jason Lengstorf.pdf - Computer Science ...

Pro PHP and jQuery by Jason Lengstorf.pdf - Computer Science ...

Pro PHP and jQuery by Jason Lengstorf.pdf - Computer Science ...

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

58<br />

CHAPTER 2 ■ COMMON JQUERY ACTIONS AND METHODS<br />

$(":submit").val("Sign In");<br />

.data()<br />

The submit button is called Sign In after running the preceding code snippet.<br />

Previously, you used the .data() method to store information for a test of .remove() <strong>and</strong> .detach(). The<br />

.data() method does exactly that: it allows you to store information about an element within the <strong>jQuery</strong><br />

object in a safe, easy manner.<br />

To give the first two paragraphs in the test document nicknames, store the information using<br />

.data() <strong>and</strong> then log it in the console:<br />

$("p:first")<br />

.data("nickname", "Pookie")<br />

.next("p")<br />

.data("nickname", "Shnookums");<br />

console.log("My nickname: "+$("p:first").data("nickname"));<br />

console.log("My nickname: "+$("p:eq(1)").data("nickname"));<br />

After executing this script, the following will be logged in the console:<br />

>>> $("p:first") .data("nick...name: "+$("p:eq(1)").data("nickname"));<br />

My nickname: Pookie<br />

My nickname: Shnookums<br />

Data can be added to an element en masse as in JSON format as well:<br />

$("p.foo").data({<br />

"nickname":"Wub<strong>by</strong>",<br />

"favorite":{<br />

"movie":"Pretty Woman",<br />

"music":"Sade",<br />

"color":"pink"<br />

}<br />

});<br />

console.log("Nickname: "+$("p.foo").data("nickname"));<br />

console.log("Favorite Movie: "+$("p.foo").data("favorite").movie);<br />

The preceding will produce the following output when executed:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!