Marko
Marko

Reputation: 72232

Working with jQuery Metadata - can't read HTML5 data attributes

I'm trying to use HTML5 data- attributes and read them with the jQuery plugin.

First of all, does the DOCTYPE matter in this case? (I'm not worried about validation)

Here's what I'm trying to do:

<ul id="quiz">
  <li data-career="math" class="first">
    <span>Question 1</span>
    <input type="radio" name="question1" />
    <input type="radio" name="question1" />
    <input type="radio" name="question1" />
  </li>
  <li data-career="science">
    <span>Question 2</span>
    <input type="radio" name="question2" />
    <input type="radio" name="question2" />
    <input type="radio" name="question2" />
  </li>
</ul>

Then THIS throws an error (a is undefined)

$.metadata.setType("html5");
$(document).ready(function() {
    var data = $("#quiz .first").metadata();
    console.log(data);
});

Also console.log(data.career) doesn't work either.

I'm using jQuery 1.4.2.

P.S. Is metadata now included as part of jQuery?

Upvotes: 5

Views: 5469

Answers (3)

Neil Aitken
Neil Aitken

Reputation: 7854

If you aren't able to the use the latest jQuery version (for whatever reason) you can still access the attributes with the .attr() method.

var data = $("#quiz .first").attr('data-career');

Upvotes: 1

David Tang
David Tang

Reputation: 93674

You're using 0.0.1 of a version too old:

As of jQuery 1.4.3 HTML 5 data- attributes will be automatically pulled in to jQuery's data object.

Usage:

$('#quiz .first').data('career');

As for the metadata plugin, I don't believe the html5 type option exists - see API. I believe you want:

$.metadata.setType('attr', 'data-career');

Upvotes: 3

Mark Coleman
Mark Coleman

Reputation: 40863

As of 1.4.3 HTML 5 data attribute were supported.

From the release notes:

For example, given the following HTML:

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

All of the following jQuery code will work.

$("div").data("role") === "page";
$("div").data("hidden") === true;
$("div").data("options").name === "John";

Upvotes: 11

Related Questions