Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "discard" form changes?

Tags:

jquery

Setup:

I have a form and a "Submit" button. Ideally the user should fill out the form, click "Submit" and then leave the tab. If he tries to leave the tab without saving the changes, I need to alert him with 3 options:

  1. Save
  2. Discard: discard the form data changes, and leave the tab, as if the data was never modified. If user comes back to the same tab, he should see the "unmodified" data.
  3. Cancel: Just dismiss the dialog box, keep the user on the same tab. User can either modify the data further, click save, etc.

Problem:

Implementing Save and Cancel is easy. The issue is with "Discard". If the user clicks "Discard", the form data should get restored to what it was before modification.

Is there any way to do this? If I haven't explained issue properly, please let me know.

like image 967
Bhushan Avatar asked Dec 12 '22 02:12

Bhushan


2 Answers

You could save the initial state of the form in the jQuery .data() function. Maybe do something like

$(function(){
    $('form').find(':input').each(function(i, elem) {
         var input = $(elem);
         input.data('initialState', input.val());
    });
});

Then once you hit discard, you could call a method, say:

function restore() {
    $('form').find(':input').each(function(i, elem) {
         var input = $(elem);
         input.val(input.data('initialState'));
    });
}

Note: this is useful if you want to restore the form to what the data was on the page without having the user leave the page. If you don't want to save the data, just don't... save the data.

like image 190
Jason Avatar answered Jan 03 '23 18:01

Jason


reset form as long as the values of the form are filled in using the value="" you can just do

<input type="button" name="reset_form" value="Reset Form" onclick="this.form.reset();">
like image 20
bretterer Avatar answered Jan 03 '23 17:01

bretterer