Here is how I did it (without using jQuery).
In my case, I wanted one particular form element not to be taken into account, because it was the element that caused the validation, and therefore will always be changed. The exclusive element is called "report_period" and is hardcoded in the "hasFormChanged ()" function.
To check, make an element that calls the "changeReportingPeriod ()" function, which you probably want to call something else.
IMPORTANT: you must call setInitialValues ββ() when the values ββwere set to their original values ββ(usually when the page loads, but not in my case).
NOTE. I am not saying that this is an elegant solution; in fact, I do not believe in elegant JavaScript solutions. My personal emphasis in JavaScript is on readability, not structural elegance (as if it were possible in JavaScript). I donβt really care about file size when writing JavaScript, because what gzip is for, and trying to write more compact JavaScript code invariably leads to unbearable maintenance problems. I do not apologize, express remorse and refuse to discuss it. This is JavaScript. Sorry, I had to make this clear in order to convince myself that I should worry about publishing. Be happy!:)
var initial_values = new Array(); // Gets all form elements from the entire document. function getAllFormElements() { // Return variable. var all_form_elements = Array(); // The form. var form_activity_report = document.getElementById('form_activity_report'); // Different types of form elements. var inputs = form_activity_report.getElementsByTagName('input'); var textareas = form_activity_report.getElementsByTagName('textarea'); var selects = form_activity_report.getElementsByTagName('select'); // We do it this way because we want to return an Array, not a NodeList. var i; for (i = 0; i < inputs.length; i++) { all_form_elements.push(inputs[i]); } for (i = 0; i < textareas.length; i++) { all_form_elements.push(textareas[i]); } for (i = 0; i < selects.length; i++) { all_form_elements.push(selects[i]); } return all_form_elements; } // Sets the initial values of every form element. function setInitialFormValues() { var inputs = getAllFormElements(); for (var i = 0; i < inputs.length; i++) { initial_values.push(inputs[i].value); } } function hasFormChanged() { var has_changed = false; var elements = getAllFormElements(); for (var i = 0; i < elements.length; i++) { if (elements[i].id != 'reporting_period' && elements[i].value != initial_values[i]) { has_changed = true; break; } } return has_changed; } function changeReportingPeriod() { alert(hasFormChanged()); }
Teekin Aug 26 '10 at 21:40 2010-08-26 21:40
source share