Using prepopulated form, submit only changed fields

前端 未结 3 1411
囚心锁ツ
囚心锁ツ 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:34

    waldol1's method works. Here I'm making a suggestion, and offering an alternate way.

    Improvement:

    For cleaner code, just use "add(this)" for each input element.

    
    

    Then, in the add() function, just add one more line to get the name of the element being clicked

    function add(e) {
        var name = e.name;
    // do stuff
    }
    

    Alternate solution:

    I'm not submitting a form the classic way; I'm just using input elements and doing stuff with Javascript. I don't care about disabling form elements, and don't want to rely on that as a flag. Instead I'm using a JS object to store my changed variables, then I just run through the object when I build my parameters (in my case, to submit via AJAX request).

    Define a global "tosubmit" object (you could use an array if you want).

    var tosubmit = new Object();
    

    For any input element I want updateable, I call add(this) when there's a change:

    
    

    The JS function adds the changed element to my temporary storage object.

    function add(e) {
    
        // Store the element and it's value, ready for use later.
        tosubmit[e.name] = e.value;
    }
    

    When I'm ready, I build parameters for my AJAX update. In my casI run the function with an ID, in my case. I run through the tosubmit object, and if the update is successful, I clear it out, ready for another use.

    function sendUpdate(id) {
    
        // Start building up my parameters to submit via AJAX to server.
        var params = "id="+encodeURIComponent(id);
    
        // Run through the tosubmit object, add any updated form elements.
        for (var i in tosubmit) {
            params = params + "&" + i + "=" + encodeURIComponent(tosubmit[i]);
        }
    
        // (Do other stuff, build my http request, etc)
    
        // Eventually submit params with the http request
        http.send(params);
    
    
    }
    

提交回复
热议问题