JavaScript判断用户是否对表单进行了修改的方法

这段JS代码可以判断用户是否对表单内容进行了修改,如果修改表单,并退出浏览器,则会提醒用户是否要保存表单的内容,是非常有用的代码。

function formIsDirty(form) { for (var i = 0; i < form.elements.length; i++) { var element = form.elements[i]; var type = element.type; if (type == "checkbox" || type == "radio") { if (element.checked != element.defaultChecked) { return true; } } else if (type == "hidden" || type == "password" || type == "text" || type == "textarea") { if (element.value != element.defaultValue) { return true; } } 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) { return true; } } } } return false; }

使用示例:当退出浏览器是,如果用户修改了表单,则提醒用户是否要保存

window.onbeforeunload = function(e) { e = e || window.event; if (formIsDirty(document.forms["someForm"])) { // For IE and Firefox if (e) { e.returnValue = "You have unsaved changes."; } // For Safari return "You have unsaved changes."; } };

下面是一个完整的范例代码

复制代码 代码如下:

Click on below button. Now change some values in form and click the button again.
<form>
    <input type="text"><br>
    <input type="text" value="default"><br>
    <select>
        <option value="fooo" selected="">foo</option>
        <option value="bar">bar</option>
    </select><br>
</form>
    <button>Click to check if Form is Dirty</button>
<br>
<script>
function formIsDirty(form) {
  for (var i = 0; i < form.elements.length; i++) {
    var element = form.elements[i];
    var type = element.type;
    if (type == "checkbox" || type == "radio") {
      if (element.checked != element.defaultChecked) {
        return true;
      }
    }
    else if (type == "hidden" || type == "password" ||
             type == "text" || type == "textarea") {
      if (element.value != element.defaultValue) {
        return true;
      }
    }
    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) {
          return true;
        }
      }
    }
  }
  return false;
}
</script>

希望本文所述对大家的javascript程序设计有所帮助。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgfypg.html