1

In jQuery I can create a HTML element with data:

$('<button onclick="btn()"></button>').data("field", { i: i, j: j }).appendTo("body");

and use it so:

function btn(){
    var field = $(this).data("field")
    alert(field.i)
}

HTML

<button onclick="btn()" data-field= "{ i: thevalueofi, j: tthevalueofj }"></button>

function btn(){
    var field = $(this).data("field")
    alert(field.i)
} // it doesn't work

How can I use data in JavaScript?

2

4 Answers 4

5

If you want the html of a button which will have the same data available as the button you created, you'll have to use the html5 data attributes. i.e.

<button data-field='{ "i": "thevalueofi", "j": "tthevalueofj" }'></button>

and read it

 function btn(){
        var field = $('button').data("field");
        alert(field.i)}
 }

with plain js

 function btn(){
        var field = JSON.parse(document.querySelector('button').getAttribute("data-field"));
        alert(field.i)}
 }
Sign up to request clarification or add additional context in comments.

8 Comments

First you need to read the attribute using .attr() and then use JSON.parse to convert the string to JSON and then read the properties of JSON as usual.
haha, how can I use it?? You don't know j'ack? You don't know i'van +1 for 30k Musa
I get syntax error if I use dataset: jsfiddle.net/mplungjan/mRRUf would you know why?
@mplungjan you get syntax error because your data-field is not json jsfiddle.net/mRRUf/9
i told someone today too, it's bad practice to have javascript inline of an attribute. Musa is again right, even without depending on semicolons, you're missing @mplungjan: stackoverflow.com/questions/5871640/…
|
1

I want to expand on Derek's comment, and on some of the other answers here to address the burning question.

ok, but how can i use it?

The data-* series of attributes are designed for storing a set of data as attributes on an HTML element, and it's designed in such a way so that you don't have to explicitly deal with data to JSON conversions yourself or store all the data in a single attribute.

Instead of storing all your data in a single data-* attribute, store the data in individual attributes, like so:

<div id="user" data-id="12345" data-name="James" data-role="developer" 
        class="users wrappers" >
     ...
</div>

Then, when you need to retrieve your data, you can retrieve it all at once with a simple JavaScript command:

var userObj = document.getElementById("wrapper").dataset;

console.info("user id = " + userObj.id); // prints "12345"
console.info("name = " + userObj.name);  // prints "James"
console.info("role = " + userObj.role);  // prints "developer"

As you can see, non-data-* attributes, like the id and class, are not included in dataset, which makes it easy to extract only the data itself.

Moreover, the userObj is similar to a pure JavaScript object, which I can confirm by stringifying it:

console.info("Stringified JSON object = " + JSON.stringify(userObj)); 
    // prints '{"id":12345,"name":"James","role":"developer"}'

However, truth be told, the object isn't a true JavaScript object but is in fact a DOMStringMap, which has limitations when it comes to nesting data, which we'll see below:

void setDataAttr(
  in DOMString prop,
  in DOMString value
);

Parameters

prop

The property whose value is to be set.

value

The property's new value.

Note that the above value is a DOMString, not an object.

In your case, you're storing all of your data as a single, stringified JSON object on a single data-* field called data-field. This isn't incorrect, but it's slightly different, and may lead to more work for you. It may have different advantages and disadvantages in regards to readability, for instance, as well as the extra work converting the string to an object.

In your case, to extract the data, you'd need to do this:

<!-- Note the nested quotes. This is what it looks like in the Chrome Elements 
     inspector. In reality, the quotes inside must be escaped -->
<div id="user" data-field="{"id":"12345", "name":"James", "role":"developer"}" 
        class="users wrappers" >

var userString = document.getElementById("user").dataset.field;

Except, here's where we begin to see holes in this methodology. The dataset.field value is not an object like it would be in the first example; instead, it's a string, and we must convert it to an object ourselves:

var userObj = JSON.parse(userString);

Now we can access the properties of the data represented by data-field:

console.info("name = " + userObj.name);  // prints the name "James"

Unlike a regular JSON object, which can contain nested JSON objects, the DOMStringMap is an object containing key/value pairs where the values are all strings. In short, any nested objects inside a value are represented as strings, not as an object, which means they must be converted to objects individually.

Again, this isn't a bad thing, but it suggests that storing objects in a single element might be better reserved for more complex data structures where the object representation is more than just one level deep. In that case, we must convert from string to JSON, but we'd have a good reason to do so in that case, since the engine won't do those conversions for us beyond just one level of nesting.

Try manipulating the data yourself from the Chrome JavaScript console, or the Firebug console, if you prefer Firefox. The console allows us to play around with different techniques in real-time and get a stronger feel for how a certain feature is supposed to work. Hope this helps!

Comments

1

With .dataset:

document.querySelector('button').dataset.field

This isn't supported in all browsers, so you may need to find a polyfill (or use jQuery).

2 Comments

@mplungjan probably if it was json
.getAttribute('data-field') also works when .dataset isn't supported.
-1

Use this javascript.

<button type="button" id="mybutton" onclick="btn()" data-field= "{ i: thevalueofi, j: tthevalueofj }"></button>
<script>
 function btn(){
   var mydata = document.getElementById("mybutton").getAttribute("data-field");
    alert("data-field");
    // alert(mydata);
 }
</script>

OR

Use jQuery like this.

<button type="button" id="mybutton" onclick="btn()" data-field= "{ i: thevalueofi, j: tthevalueofj }"></button>
<script>
 function btn(){
   var mydata = jQuery("button#mybutton").attr("data-field");
    alert("data-field");
    // alert(mydata);
 }
</script>

2 Comments

This is not how you get value in data-field... See this: developer.mozilla.org/en-US/docs/DOM/element.dataset
Hey Bharat, did you mean to alert the data itself instead of simply alerting the hard-coded text "data-field"?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.