Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET mvc detect clientside changes

In my application I want a customer to not press submit when he didn't change values in a specific form. I can do this serverside and add a viewmodelerror to the modelstate. But is there a way to do this also clientside with javascript? I searched for it, but couldn't find it.

like image 240
Patrick Avatar asked Nov 15 '11 08:11

Patrick


1 Answers

You can set a javascript variable if the form is edited. A simple way of doing this would be to listen to the change event on input fields:

var isChanged = false;
$('input,select,textarea').change(function() {
  isChanged = true;
});

And then check for isChanged before submitting.

This approach doesn't deal with values being changed back to the original value though.

If you need to address that scenario, you would need to keep the form state in a javascript object and compare it with that.

You could add this to avoid the user to leave the page if the form has changed:

$(window).bind('beforeunload', function() { 
  if (isChanged) {
    return 'You have changed the form, are you sure?';
  } else {
    return undefined;
  }
});
like image 199
Christian Dalager Avatar answered Oct 08 '22 18:10

Christian Dalager