I have a form generated by <% Ajax.BeginForm() {} %>
which contains a lot of inputs and texareas.
When an input value change, I need to know about it and mark the input and the form as "dirty". If the user tries to leave the page without saving, I will ask him or her to confirm abandoning changes.
Any suggestion to how this should be done?
I would do this with jQuery. It would be something like this (just a draft, you may need to add/change some code):
Then, before POSTing, check if there is a dirty input. You can even add some color by using the dirty css class.
EDIT: typo fixed 'changed' to 'change'
From jQuery Docs:
And you could do like this to check only the inputs and have user notified, if they try to exit without saving changes.
jQuery API .change()
You could use jquery plugin dirrty for identifying form dirty.
https://github.com/rubentd/dirrty
In on("dirty") event set some global variable to true to identify form has changed.
Handle
window.onbeforeunload
or$(window).unload()
event and get confirmation from user based on that variable value.The advantage of this plugin is you can track back if form is changed to original values again using 'on("clean") event
Resurrecting this old question because I thought of a simpler/better way. Instead of listening to events on the various inputs, you can serialize the initial form data, store it, and then serialize it again later and check if it's changed, like this:
One additional advantage here is that if the user makes a change and then reverts it, this check will report the form as clean.
The html controls include a property that holds the original value. You could compare this value with the current value to see if there have been any changes.