Javascript: fast way to check if form contents have been changed before submission

别说谁变了你拦得住时间么 提交于 2019-12-06 11:07:25

问题


Simple question (I guess)... I'm in an "edit-some-element" html form. As the page load, the form is filled with current element attributes (eg. name, etc.) I could modify some input fields or even decide not to do that but I click the same on submit button because is the only available one.

MY QUESTION: is there a property/attribute of the input elements containig the initial input values that I can access to compare them with the current ones when I click on submit button? In other words: is there a fast way to check if at least one input field has been changed before submitting the form? (so to stop the event if an update isn't really necessary) (and I mean "really changed" not considering as changes when I modify something but rewrite it as it was before)

I'd like a minimal example: How to check if a simple input-text "name" has been changed

P.S. Of course, to trigger the "check-if-something-changed" function, if I decide to use pure javascript I would use onSubmit event while using jQuery I would use something like:

$('#formMod').submit(function(){ ...

Thanks.


回答1:


You can use the input element defaultValue dom property:

function validateInput(input) {
    if (input.value == input.defaultValue) {
        alert("Please change field.");
        return false;
    }
    return true;
}


来源:https://stackoverflow.com/questions/8369683/javascript-fast-way-to-check-if-form-contents-have-been-changed-before-submissi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!