1

I have a select-box where a user can pick a value which populates a text-box and the user can edit the value (with Ajax). Every option in the selectbox has an id and a data-critical attribute. I use the JQuery 'change' event handler to populate a textbox with the value in the data-critical.

<select id="actions">
  <option id="p0" data-critical="100"  value="0">Optie 0</option>
  <option id="p1" data-critical="120"  value="1">Optie 1</option>
</select>

<input type="text" id="editcritical" />

$("#actions").change(function() {
  var selected = $(this).find('option:selected');

  $("#editcritical").val(selected.data('critical'));
});

ajax-success: function(data){
  $("#p" + data.p.id).attr("data-critical", data.p.critical);
}

On Ajax success the data-critical value is changed, but when I select the option again, the old value is displayed in the text-box. I tried to use the Live method, but nothing happened. Firebug shows the updated value in data-critical.

Any suggestions to show the updated value in the text-box?

cooxie
  • 2,934
  • 5
  • 18
  • 17

2 Answers2

1
$("#actions").change(function() {
  var selected = $(this).find('option:selected');

  $("#editcritical").val(selected.attr('data-critical'));
});

Within you success function you should try:

success: function(data){
  $("#p" + data.p.id).data("critical", data.p.critical);
}

Read jQuery data() vs attr(data) to know more.

Community
  • 1
  • 1
thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
0

Did you try it with:

$("#editcritical").attr("data-critical");

?

Chris
  • 4,255
  • 7
  • 42
  • 83
  • I can get and update the value from data-critical. The problem is when the data-critical value is changed after the Ajax call, and I select the option again with the updated data-critical value, the older value is shown in the text-box instead of the new value. – cooxie Jun 03 '12 at 16:28
  • Is your further code in the .done/.success-method of the ajax call? – Chris Jun 03 '12 at 16:30
  • That's why you should replace $("#editcritical").val(selected.data('critical')); with $("#editcritical").attr("data-critical"); as suggested. – Abhijit Jun 03 '12 at 16:37
  • @Abhijit: #editcritical doesn't has an attr 'data-critical', data-critical is an attr from the option from the selectbox – cooxie Jun 03 '12 at 16:57
  • @cooxie Sorry, I did not notice the id's of select or option, just was referring to using attr instead of data. – Abhijit Jun 03 '12 at 17:50