Reputation: 81
I have this function that modify my existing object by ID :
var updateUser = function () {
var id = $("#userId").val();
var user = findObjectById(id);
user.username = $('#username').val();
user.level = $('#level').val();
user.regstatus = $('#regstatus').val();
user.regdate = $('#regdate').val();
$(".table").show();
$("#newUser").show();
$("#userForm").hide();
$("#updateUser").hide();
};
How can i replace my curent data from HTML with modified data ?
This is my function for creating rows :
var buildRow = function (data) {
var html = '<tr id = ' + data.id + '>' +
'<td>' + data.username + '</td>' +
'<td>' + data.level + '</td>' +
'<td>' + data.regstatus + '</td>' +
'<td>' + data.regdate + '</td>' +
'<td>' +
'<button class="btn btn-info"value="Edit" onclick="userList.editUser(' + data.id + ')">Edit</button>' + ' ' +
'<button class="btn btn-danger" value="Delete" onclick="userList.deleteRow(' + data.id + ')">Delete</button>' + '</td>' +
'</tr>';
$("#users").append(html);
};
P.S i want to update in the same place and my id should be the same.
Upvotes: 0
Views: 2494
Reputation: 1494
I modified your prototype jsFiddle a bit, so it contains a working example.
I needed to modify some parts to get it work, for example updating the object I added a function.
updateObjectById = function (id, obj){
for (var i = 0, l = userData.length; i < l; i++) {
if (userData[i].id == id) {
userData[i] = obj;
}
}
};
You should be able to work it out I guess, by the given jsFiddle
Upvotes: 1
Reputation: 1034
As I understand it you want to update the table when running "updateUser". There are basically three ways to update the data in your case.
In my experience the best solution, and how f.ex. Backbone does it, is just recreating all the HTML when your data changes. two way databinding is even more powerful, but seems overkill in this situation.
So basically in your updateUser function:
var row = buildRow(user);
var $existingRow = $(id);
if ($existingRow.length) {
$existingRow.replaceWith(row);
} else {
$('#users').append(row);
}
Now, this of course requires a change to your "buildRow" function, not making it append the row, but return it.
Hope this gets you further...
Upvotes: 0