Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do we implement a cancel in plain Javascript?

I have a page and I display data in a table.
In each table I have a column with a checkbox which if is checked the user can modify the specific row via Javascript.
This is done as its td encapsulates either an input or a select and I make these editable for the user.
The user modifies the row and presses save and the changes are saved. So far ok.
My problem is how do I implement a cancel?
The user could choose many row i.e. check boxes and modify them but the user could also press cancel. On cancel the original values should be displayed (and the rows become non-editable again).
But how is a cancel operation implemented in Javascript? Do we store data in some global datastructures? Which would be this in Javascript?

like image 870
Cratylus Avatar asked Jun 03 '13 19:06

Cratylus


1 Answers

Ok, after the addition of informations you provided I suggest you setup the following mecanism:

function getDatas() {
var oXhr;

    //get datas from database:
    oXhr = new XMLHttpRequest();    
    oXhr.onreadystatechange = function() {
    if (oXhr.readyState == 4 && (oXhr.status == 200)) {
        g_oData = (new DOMParser()).parseFromString(oXhr.responseText, "text/xml");
        }
    }

    oXhr.open("POST", "yourphpscriptthatreturnsthexmldatas.php", true);
    oXhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");
    oXhr.send();
}

function populateGrid() {
    //use g_oData to populate your grid, but at first totally clean the body
    var mygrid = document.getElementById("mygridid");
    //mygrid.innerHtml = "<table><tr><td>...</td></tr></table>";

    //use the xml library to parse g_oData and fill up the table:
    var xmlRows = g_oData.getElementsByTagName("TAG");
    var xmlRow;
    iLen = xmlRows.length;
    for (var i=0;i<iLen;i++) {
    xmlRow = xmlRows[i];
    //use xmlRow->textContent to build each cell of your table
    }
}

function revertChange() {
    //on cancel, revert the changes by populating the grid. 
    //it will use the global xml/json object loaded directly from database, to refill everything.
    populateGrid();
}

I did it myself many times to refresh some datas in a page. That's basically what you're doing except that you're not requesting anything to the database, you just refill the fields.

like image 57
Sebas Avatar answered Oct 15 '22 20:10

Sebas