0

What don't I understand about .data()?

Here are two divs:-

<div id="dataObjects">
  <div id="dataGetterClone"></div>
</div>

Here is my code:-

for (var i = 0; i < 4; i++) { 
 var elementid = "dataGetter";
 $("#" + elementid + "Clone")
  .clone()
  .attr('id',elementid + i.toString())
  .addClass("newItem")
  .data('dflt_internal_ID'   ,"")
  .data('dflt_elem_category' ,"Category")
  .data('dflt_elem_type'     ,"Standard")
  .data('dflt_elem_name'     ,"Getter " + i.toString())
  .data('dflt_elem_top'      ,20)
  .data('dflt_elem_left'     ,40)
  .data('dflt_elem_height'   ,60)
  .data('dflt_elem_width'    ,80)
  .appendTo($("#dataObjects"));
}
// keep track of number of changes to be saved, and display error later if there are none
var itemCount = 0;

// prepare items to be inserted
var createdOn = new Date();
$( "#dataObjects > .newItem" ).each( function() {
  $(this).data("created_by", 57);
  $(this).data("created_on", createdOn);
  itemCount++;
  alert($(this).data().count);
});

alert("count of inserts " + itemCount);

Here is my fiddle.

Why does alert($(this).data().count); return "undefined"?

cneeds
  • 319
  • 3
  • 10
  • 3
    What's `.count`? Do you mean `.length`? – j08691 Nov 19 '14 at 15:04
  • Yes. Same result if I use .length – cneeds Nov 19 '14 at 15:08
  • `.data()` doesn't return an array but an object, which doesn't have a length property. – JJJ Nov 19 '14 at 15:09
  • Use `console.log( $(this).data() )` instead and look in the browser's JS console. – JJJ Nov 19 '14 at 15:09
  • Thank you @Juhana, the data is there, but how do I know how many attributes? Alternatively can I store or convert the .data() to an array (albeit in another variable?)? – cneeds Nov 19 '14 at 15:15
  • http://stackoverflow.com/questions/126100/how-to-efficiently-count-the-number-of-keys-properties-of-an-object-in-javascrip – JJJ Nov 19 '14 at 15:16
  • OK, that's probably why .count didn't throw an error? And I can use the same loop to convert to an array. Thank you. – cneeds Nov 19 '14 at 15:20
  • For future reference var itemData = $.makeArray($(this).data()); converts the object to an array. See http://api.jquery.com/jquery.makearray/ – cneeds Nov 19 '14 at 16:06
  • Is it possible to see the contents of the .data() attributes using firebug? – cneeds Nov 20 '14 at 04:39

0 Answers0