HTMLInputElement's defaultValue
Posted on: April 17, 2012
Did you know that you can know the original value written by the server to the client by calling:
1var originalName = document.getElementById("txtUserName").defaultValue;
Yes, the Dom contain for every Html element of type HTMLInputElement
and HTMLTextAreaElement
the possibility to access the original value. This is interesting to know if a form has dirty inputs. It's also interesting because it removes the need to hide values into hidden fields or to hide into a Javascript object all original values.
From the ECMAScript's specification we can see that it's a property that return a string. It's also possible to know if the value was originally checked in the case of a checkbox with defaultChecked
.
From here it's easy to know if a Html form is dirty (has something changed). We just need to loop through all inputs and compare.
1function TestDirty(){2 var formDirty = false;3 $('#frm :input').each( function(){45 if($(this).is("input")) {6 //alert('Name :' + $(this).attr('name') + ">" +$(this).val()+ " != " + $(this)[0].defaultValue);7 var type = $(this).attr('type');8 if (type == "checkbox" || type == "radio") {910 if ($(this).is(':checked') != $(this)[0].defaultChecked) {11 //alert('Form dirty by' + $(this).attr('name') + ">" +$(this).is(':checked')+ " != " + $(this)[0].defaultChecked);12 formDirty = true;13 }14 } else if (type == "hidden" || type == "password" || type == "text") {15 if ($(this).val() != $(this)[0].defaultValue) {16 //alert('Form dirty by' + $(this).attr('name') + ">" +$(this).val()+ " != " + $(this)[0].defaultValue);17 formDirty =true;18 }19 }20 } else {21 var type = $(this).get(0).tagName;22 if (type == "TEXTAREA") {23 if ($(this).val() != $(this)[0].defaultValue) {24 //alert('Form dirty by' + $(this).attr('name') + ">" +$(this).val()+ " != " + $(this)[0].defaultValue);25 return formDirty;26 }27 } else(type == "SELECT") {28 alert('Form dirty by ' + $(this).attr('name') + ">" +$(this).val()+ " != " + $(this)[0].defaultSelected);29 if ($(this).val() != $(this)[0].defaultSelected) {30 //alert('Form dirty by' + $(this).attr('name') + ">" +$(this).val()+ " != " + $(this)[0].defaultValue);31 return formDirty;32 }33 }34 }35 });3637 return formDirty;38}
You can have the above code functional here. The only case that doesn't seem to work is the select box which the value is undefined. If someone has the code to fix it, feel free to post it.