Using prepopulated form, submit only changed fields

前端 未结 3 1413
囚心锁ツ
囚心锁ツ 2021-02-11 03:45

I have an html form that uses select and text inputs. The form comes pre-populated with default values. How can I submit only the inputs that were changed by the user from the

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-11 04:41

    As per Barmar's suggestion to use an array to track which values have changed, this is the solution I have come up with and it works.

    Here is the js:

    var tosubmit = []
    function add(name) {
        if(tosubmit.indexOf(name) == -1)
            tosubmit.push(name);
    }
    
    function is_changed(name) {
        for(var k = 0; k < tosubmit.length; k++)
            if(name == tosubmit[k])
                return name && true;
        return false;
    }
    
    function before_submit() {
        var allInputs = document.getElementsByTagName("input");
        var allSelects = document.getElementsByTagName("select");
        for(var k = 0; k < allInputs.length; k++) {
            var name = allInputs[k].name;
            if(!is_changed(name))
                allInputs[k].disabled = true;
        }
        for(var k = 0; k < allSelects.length; k++) {
            var name = allSelects[k].name;
            if(!is_changed(name))
                allSelects[k].disabled = true;
        }
    }
    

    html:

    This works because form elements that are disabled are not included in the POST Request. Thanks everyone for their suggestions.

提交回复
热议问题