HTML and CSS Reference
In-Depth Information
Listing 6-15. Using jQuery to Access data-* Attributes
alert('Employee ID : ' + $("#emp1").data('employeeid'));
alert('Title : ' + $("#emp1").data('title'));
$("#emp1").data('employeeid', '100');
$("#emp1").data('title', 'Senior Manager');
alert('Employee ID : ' + $("#emp1").data('employeeid'));
alert('Title : ' + $("#emp1").data('title'));
The jQuery library provides a data() method to access custom data attributes. To retrieve a data-*
attribute, you call data() on the underling DOM element and pass the attribute name without data- . For
example, Listing 6-15 uses data('employeeid') to retrieve the value of the data-employeeid attribute. To
assign a value to a data-* attribute, you call the data() method and supply the attribute name without
data- and its new value. If the custom data attribute contains hyphen ( - ) in the name ( data-employee-
birthdate , for example) you can access it using the same camel-casing syntax, as shown here:
alert('Title : ' + $("#emp1").data('employeeBirthdate'));
If you call data() without any parameters, it returns an object of key-value pairs containing all the
data-* attributes of that element and their values. Listing 6-16 shows how to use this variation of the
data() method.
Listing 6-16. Using the data() Method to Obtain data-* Attributes as an Object
var obj = $("#emp1").data();
alert('Employee ID : ' + obj.employeeid);
alert('Title : ' + obj.title);
alert('Birth Date : ' + obj.employeeBirthdate);
As you can see, the data() method is called without any parameters. Doing so returns an object with
key-value pairs. To read a particular data-* attribute value, you can use the data-* attribute name without
data- against the object returned.
n Note You can also use the jQuery attr() method to get or set data-* attributes. However, it's better to use
data() because it's designed specifically to deal with custom data attributes.
Using Custom Data Attributes to Emit Validation Messages
Now that you know how to use custom data attributes, let's develop a Web Forms application that
illustrates how you can implement the validation scenario discussed at the beginning of this section with
the help of data-* attributes. In this section, you develop a web form as shown in Figure 6-6.
Search WWH ::

Custom Search