I’ve got the following field on an MVC view:
@Html.TextBoxFor(model => model.Course.Title, new { data_helptext = "Old Text" })</span>
In a seperate js file, I want to set the data-helptext attribute to a string value. Here’s my code:
alert($(targetField).data("helptext"));
$(targetField).data("helptext", "Testing 123");
The alert() call works fine, it shows the text “Old Text” in an alert dialog. However, the call to set the data-helptext attribute to “Testing 123” does not work. “Old Text” is still the attribute’s current value.
Am I using the call to data() incorrectly? I’ve looked this up on the web, and I can’t see what I’m doing wrong.
Here’s the HTML markup:
<input data-helptext="Old Text" id="Course_Title" name="Course.Title" type="text" value="" />
It is mentioned in the
.data()documentationThis was also covered on Why don't changes to jQuery $.fn.data() update the corresponding html 5 data-* attributes?
The demo on my original answer below doesn’t seem to work any more.
Updated answer
Again, from the
.data()documentationSo for
<div data-role="page"></div>the following is true$('div').data('role') === 'page'I’m fairly sure that
$('div').data('data-role')worked in the past but that doesn’t seem to be the case any more. I’ve created a better showcase which logs to HTML rather than having to open up the Console and added an additional example of the multi-hyphen to camelCase data- attributes conversion.Updated demo (2015-07-25)
Also see jQuery Data vs Attr?
HTML
JavaScript (jQuery 1.6.2+)
Older demo
Original answer
For this HTML:
and this JavaScript (with jQuery 1.6.2)
See demo
Using the Chrome DevTools Console to inspect the DOM, the
$('#foo').data('helptext', 'Testing 123');does not update the value as seen in the Console but$('#foo').attr('data-helptext', 'Testing 123');does.