I'm trying to use jQuery's data() function to store and retrieve data on an element. I want to retrieve the data stored in a textarea whenever the user enters the space bar1. However, everytime I do this I get undefined
back from data()
.
Now, if I define exactly the same Javascript in the HTML, it works as expected. Is there some "gotcha" to data()
that keeps it from working in GreaseMonkey?
Here is the GreaseMonkey script:
(function(){
//boilerplate greasemonkey to wait until jQuery is defined...
function GM_wait()
{
if(typeof unsafeWindow.jQuery == 'undefined') {
window.setTimeout(GM_wait,100);
} else {
var $ = unsafeWindow.jQuery;
$(function() { letsJQuery($); });
}
}
GM_wait();
function letsJQuery($)
{
//store the data initially
$('textarea[name=comment]').data('tst', 'abc');
//retrieve the data on spacebar
$('textarea[name=comment]').live('keypress', function(e) {
if(e.which == 0x20) { //spacebar
alert("the stored data is: " + $(this).data('tst'));
return false;
}
});
}
})();
And here is my very simple test HTML file:
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
</head>
<body>
<textarea name="comment"></textarea>
</body>
</html>
1 This is a very simplified version of my problem, of course.