Reputation: 2790
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.
Upvotes: 8
Views: 9202
Reputation: 6643
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;
}
});
Upvotes: 18
Reputation: 39898
What is the client supposed to change?
If, for example. it's just the value of a text field you could save the original value in the document ready jquery event and when hitting the submit button run a javascript function that checks if the value has changed.
If you have more complex input fields you can still use this mechanism to save the original and check on submit trough javascript.
Upvotes: 0
Reputation: 24515
Not sure what you asking? Are you talking about client side validation? in this case you could use MVC Validation or a javascript library like jquery and use a validation plugin
Upvotes: 0