How to rollback actions through javaScript?
I am having a JSP page where the user will be displayed with a table consisting rows. If the user wishes, he may add a new row and press the save button, which will insert the data into the table, which is done through JavaScript.
My request is that, user adds a new row and enters the details in that. If he clicks the reset button, it clears the data entered inside the new row but not removes the entire giving the origina开发者_如何学Pythonl data which was displayed when user started.
Please help me.
I believe your question comes in two parts: First, the new rows will need to be cleared; Second, if you are using AJAX to update data on the server then remember to sync the reset.
@321X is correct in saying that you'll just need to add an additional attribute to each row so it can be easily cleared. When you add a row I might suggest storing each Object of data into another object using unique identifiers so on reset you can loop through each item and update the server (if that's necessary). Here is some rough js-pseudo-esk code ($ === jQuery
):
var newRowsList = {};
$('.addRow').click(function( ev ) {
var newRow = {};
// populate newRow with user-data and add it to the master list
newRowList[ /* uid */ ] = newRow;
// if you are using AJAX to sync row-by-row changes:
$.ajax({
// url, post, etc...
success : function() {
// now generate the DOM elements however you want
// add the new row to the table
$( /* row data */ ).appendTo( '#dataTable' );
}
});
});
$('#resetTable').click(function( ev ) {
for ( var i in newRowsList ) (function( item, data ) {
$.ajax({
// url, post, etc...
success : function() {
// destroy the row by using the uid passed in
$( '.' + item ).remove();
// and remove the item from the list
newRowsList[ item ] = null;
}
});
})( i, newRowsList[ i ]);
});
Not pretty, but hopefully it explains the point. Depending on how advanced this needs to be, you could add the removed items to a sequence list so if the user accidentally clicks on the reset button the change could then be reverted.
You can detect what is new and what is not.
There are several ways to do that. Certainly with jQuery, or other javascript libraries.
See my jQuery example at jsFiddle: http://jsfiddle.net/Xvm9L/
I have added an extra attribute to a new row. Remove the rows where the isnew attribute is true. This attribute should be added to the row when clicking at the New Row button or so.
Here is a version that works with plain javascript: http://jsfiddle.net/Xvm9L/1/
精彩评论