- <form>
- <input type="text" value="defaultValue 1"/>
- <input type="text" value="defaultValue 2"/>
- <textarea >defaultValue 1</textarea>
- <textarea >defaultValue 2</textarea>
- <input type="radio" name="a" />test
- <input type="radio" name="a" checked="checked"/>defaultChecked
- <input type="checkbox" name="b"/>test
- <input type="checkbox" name="b" checked="checked"/>defaultChecked
- <input type="checkbox" name="b" checked="checked"/>defaultChecked
- <select>
- <option selected="selected">defaultSelected 1</option>
- <option>test</option>
- <option>test</option>
- <option>test</option>
- </select>
- <select multiple="multiple">
- <option>test</option>
- <option selected="selected">defaultSelected 1</option>
- <option selected="selected">defaultSelected 2</option>
- <option>test</option>
- </select>
- <input type="button" onclick="IsFormChanged()" value="submit"/>
- </form>
- <script>
- function IsFormChanged() {
- var isChanged = false;
- var form = document.forms[0];
- for (var i = 0; i < form.elements.length; i++) {
- var element = form.elements[i];
- var type = element.type;
- if (type == "text" || type == "hidden" || type == "textarea" || type == "button") {
- if (element.value != element.defaultValue) {
- isChanged = true;
- break;
- }
- } else if (type == "radio" || type == "checkbox") {
- if (element.checked != element.defaultChecked) {
- isChanged = true;
- break;
- }
- } else if (type == "select-one"|| type == "select-multiple") {
- for (var j = 0; j < element.options.length; j++) {
- if (element.options[j].selected != element.options[j].defaultSelected) {
- isChanged = true;
- break;
- }
- }
- } else {
- // etc...
- }
- }
- alert( isChanged?"你改变了表单的默认值.":"成功提交.");
- return isChanged;
- }
- </script>
有2点注意
1,表单元素都有默认值属性,比如element.defaultValue , element.defaultChecked ,element.options[j].defaultSelected
2,select元素的type类型是:""select-one"或者"select-multiple",而不是"select"。