shaker
shaker

Reputation: 81

How can i update data in html after modify the object?

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

Answers (2)

Steven
Steven

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

christianalfoni
christianalfoni

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.

  1. Rebuild the whole row
  2. Pick out specific cells in the table and change the content
  3. Use a two way databinding framework

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

Related Questions