I am trying to change a data attribute, but it never seems to get changed and remains as \"TEXT\", which is the default.
function SuccessGetActorsForGroupCal
The .data method doesn't alter the data-
HTML attribute; it alters a variable that jQuery stores internally.
If you really need/want to alter the data-
attribute, do so explicitly with the .attr()
method:
$(el).attr('data-original-title', str);
However, this won't alter the value returned by .data
. jQuery will fetch that value from the data-
HTML attribute only if it can't find the value stored internally. If you retrieve $(el).data('original-title')
again after altering the HTML attribute, you'll find it hasn't changed.
If this is a a problem, use the .removeData() method to delete the internally-stored value. The next time you use .data()
, jQuery will see that it's missing and retrieve the data-
HTML attribute.
Take a look: http://jsfiddle.net/mblase75/LHCUK/
HTML:
<p id="p" data-title="blah"></p>
jQuery:
console.log($('#p').data('title')); // returns "blah"
// alter the attribute directly
$('#p').attr('data-title','whooo'); // data-title="whooo"
// test if .data is changed
console.log($('#p').data('title')); // still returns "blah"
// delete the .data() value
$('#p').removeData('title');
// now fetch it again -- it will retrieve the new data- attribute
console.log($('#p').data('title')); // returns "whooo"
Now, in practice, you shouldn't have to worry about this. Just remember that the data-
attribute represents the initial value of a .data()
variable and not necessarily the current value of that variable, and you'll be fine.
In summary: The .data()
method retrieves a value from the HTML element once when the document is loaded, and will not do so again as long as the variable is stored internally.
Your code: $(el).data('original-title', str);
should be: $(el).attr('data-original-title', str);
.attr();
is used to change attributes if used in key - value pairs.
Documentation here