We help IT Professionals succeed at work.

jquery.data not working

I am trying to use jquery.data to store some information.  I can set it, then immediately retrieve it and everything works well.  For some reason, if I try to retrieve it at a later time, I get undefined.  I am logging my data to the console so I can see what is going on.

I have a simplified version in the html file below...
<html>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script type="text/javascript">
        
function test(setVar)
{

                console.error("*********InFunction**********************");
                var tmpSelector = "#aspnetForm";
                var tmpFormObj = $(tmpSelector);
                console.error("selector=" + tmpSelector);
                console.error("id from object=" + tmpFormObj.attr('id'));
                
				if(setVar == true){
                console.error("about to set using jquery data");
                jQuery.data(tmpFormObj, 'mykey', 'MyValue');
				}
                
                var returnedData = jQuery.data(tmpFormObj, 'mykey');
                console.error("returnedData=" + returnedData);
                console.error("END Function**********************");
 }
$(document).ready(function() {
  test(true);
  test(false);
}); 
    </script>
<body>
<form name="aspnetForm" method="post" action="Locations.aspx?tab=Locations" onsubmit="javascript:return WebForm_OnSubmit();" id="aspnetForm">tes</form>

</body>

Open in new window

Comment
Watch Question

Owner (Aidellio)
Most Valuable Expert 2015
Commented:
try this
function test(setVar) {

    console.log("*********InFunction**********************");
    var tmpSelector = "#aspnetForm";
    var tmpFormObj = $(tmpSelector);
    console.log("selector=" + tmpSelector);
    console.log("id from object=" + tmpFormObj.attr('id'));

    if (setVar === true) {
        console.log("about to set using jquery data");
        //jQuery.data(tmpFormObj, 'mykey', 'MyValue');
        tmpFormObj.data('mykey','MyValue');
    }

    //var returnedData = jQuery.data(tmpFormObj, 'mykey');
    var returnedData = tmpFormObj.data('mykey');
    console.log("returnedData=" + returnedData);
    console.log("END Function**********************");
}
$(document).ready(function() {
    test(true);
    test(false);
});

Open in new window

RobOwner (Aidellio)
Most Valuable Expert 2015

Commented:
see the 2 lines i've commented out.  I'm using the .data() specific to the object you are setting the value against.  There are issues using the jQuery.data() when going in and out of context, such as a function