jQuery Tip: Brute Force Dirty Form Detection

If you disable your “save” button on your MVC views when the page first loads and want them to be auto-enabled when any input on the form changes, you can do that with the following jQuery snippet.

This is sort of a hack*, but it works.

With this HTML


<input type="submit" id="myButton" value=" Save " disabled />

and this javascript:


<script>
 $(function () {
$(":input").change(function () {
// if any input element changes, enable the save and undo buttons
$("#<%=myButton.ClientID %>").removeAttr('disabled');
});
 });
</script>

You’ll “enable” the button when the form inputs are changed. This is kind of nice when you have a TON of inputs on the page and you need to be able to detect when ANY of them have changed.

* Why its a Hack: I’m not limiting the selector to an ‘id’ therefore sizzle scans the entire DOM which could be a bummer in regards to performance).

Android Dev Digest

Get the best Android Developer posts delivered weekly to your inbox.

Don't worry, I wont spam (I hate that stuff too).

Book 15 Minutes

  • Mike Nistler

    How about using jQuery's “.one()” method? It'd unbind after one change and not incur the overhead of repeatedly attempting to remove the 'disabled' attribute.

    But as the documentation at http://api.jquery.com/one/ says, the event handler is still initially attached to each <input> selected – so if you have X <input> tags, worst case you still get X invocations. Maybe unbinding from the event is the answer once any form field is changed.