developer-x developer-x - 9 months ago 46
Javascript Question

Form values are overwritten after change

I have a form that shows up when each row in a table is double clicked. The values of this form can be updated and the form should be submitted with all row changes. But each time I double click on a row and edit the values of that form for that row, the previous values I had changed get overwritten. In order to work around this, I tried adding all the changes to a map with the row id as the key and the values of the form as the value. But the form still won't update with the new values. Here is a fiddle to demonstrate what I mean:

If I double click on the row that says "Adam Smith" and change that name to John Doe, when I double click on the second row and then double Click on "Adam Smith" again, it should say "John" on the first textbox and "Doe" on the second one. But the new value never seems to save.

This code snippet loops through each key, then loops through each value of that key:

for(var i = 0; i<key.length; i++){
var getval = globalchanges[key[i]];
for(var k=0; k<getval.length; k++){

How can I get the new changes to save? (The table rows don't have to show the changes, just the textbox values). Any help would be appreciated.

Answer Source

First, as mentioned by @Taplar you are binding the click event multiple times. Your approach is close enough, the idea of storing the changes is valid. You should have 2 functions, store the changes on button click and the second one to retrieve the changes by id.

Updated Fiddle

This function will get the values of the form and will store in on a global object

function setMap(id){
    var firstrow =  $("#input1").val();
    var secondrow = $("#input2").val();
    globalchanges[id] = [firstrow,secondrow];

This other function will check if the global object has values for the passed id, if not, it will use the values on the row

function getMap(id, tr){
    if(globalchanges[id] != undefined && globalchanges[id].length == 2){

Please note there are also changes on the dbclick and click events, they should be separated

$("#table tr").dblclick(function(){
    $("#txtbox-wrapper").css({"display" : "block"});
    var id = $(this).find('td').eq(0).text();
    var id = $('#id').val();

And that we added and additional input to store the id on the form.