tun_eng
tun_eng

Reputation: 133

data attribute of HTML 5 is undefined

In my JSP, in the head part, I have this :

<script type="text/javascript">
    $(document).ready(function() {
        var labelfooter = jQuery("#myId").data("mylabel");
        var htmlContent = labelfooter +" society ";
        var divContent = jQuery("#myId");
        divContent.text(htmlContent);
    });
</script>

Then, in the body part, I have :

<div id="myId" data-mylabel="Hello" ></div>

As a result, in the browser, I get "undefined society" instead of "Hello society"

Any idea please ?

Upvotes: 2

Views: 2348

Answers (1)

epascarello
epascarello

Reputation: 207501

The problem here is the fact you have an uppercase in your name. That means something different in the jQuery selctor. Two ways to fix it.

HTML

<div id="d1" data-fooBar="asdf1"></div>
<div id="d2" data-foo-bar="asdf2"></div>

JavaScript

var x1 = $("#d1").data("foobar"); //selects the camel case one
var x2 = $("#d2").data("fooBar"); //looks for the dash

Example

JSFiddle Example

Upvotes: 5

Related Questions