Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 690
Marko Avatar asked Feb 22 '11 21:02

Marko


3 Answers

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";
like image 143
Mark Coleman Avatar answered Nov 03 '22 00:11

Mark Coleman


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');
like image 24
David Tang Avatar answered Nov 02 '22 23:11

David Tang


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');
like image 38
Neil Aitken Avatar answered Nov 02 '22 23:11

Neil Aitken