2

I am appending some HTML to a doc. Part of the HTML is a text input. When I enter info in this input, I want to update the value of the closest li's data value.

Currently this isn't working. However, if I change the data('name'..) to CSS it works. I have checked that the value is being assigned, and it is.

Any ideas why this isn't working? Thanks in advance.

$(document).on('keyup','.image-name', function() {
     var value = $(this).val();
     $(this).closest('li.image').data('name', value);
}).keyup();
lewisjb
  • 678
  • 10
  • 26
T2theC
  • 542
  • 3
  • 10
  • 23

2 Answers2

2

I have managed to fix this after a little research. Still not sure why it isn't working but...

I have changed the data('name', value) to attr('data-name', value) and bingo...

$(document).on('keyup','.image-name', function() {
     var value = $(this).val();
     $(this).closest('li.image').attr('data-name', value);
}).keyup();
T2theC
  • 542
  • 3
  • 10
  • 23
1

there are few gotchas when using attr() vs data() Short version - data() will keep your data in memory and will not set attribute on the html element, but you can still retrieve it, even if you set throuhg attr() before, but it doesn't work quite well other way.

Here's a nice post with examples - jQuery Data vs Attr?

Hope it helps.

Community
  • 1
  • 1
Pavdro
  • 411
  • 1
  • 9
  • 18