How to reset form state with model data?

0

I have a model in which I fill in the fields of a form (use asp.net mvc and the view is typed), that is, I load the fields of this form according to the data of the database for the user to change on the screen

What I want to do is a "undo" button that resets to the initial state of the data that came from the database, not simply using this.meuform.reset () at the click of the button.

I believe that it should be done in form onLoad () a way to save the current elements of the form and when clicked on the button, simply play again on the elements, these elements saved ...

I prefer pure Javascript.

    
asked by anonymous 07.08.2015 / 15:10

1 answer

1

reset() as explained in the documentation ...

  

The HTMLFormElement.reset () method restores a form element's default values

should reset the value of the elements to the original state, and not clean them, leaving blank or things like that example .

What can be done in your case - which has multiple forms - selects them and in a reset loop at all:

var forms = document.getElementsByTagName("form");
// ou
// var forms = document.querySelectorAll("form");

for (var i = 0; i < forms.length; i++)
{
    forms[i].reset();
}

Or with jQuery:

var forms = $("form");

for (var i = 0; i < forms.length; i++)
{
    forms[i].reset();
}

Demos 1 , 2 or with more elements .

UPDATE:

To get only the first (or only) form of the screen:

var forms = document.getElementsByTagName("form");
// ou
// var forms = document.querySelectorAll("form");

if (forms.length > 0)
{
    forms[0].reset();
}

In this way you avoid possible exceptions if the routine tries to reset a form that does not exist.

    
07.08.2015 / 19:25