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?
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";
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');
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With