Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using prepopulated form, submit only changed fields

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 their default values? Note that this page is to be stored in an embedded system with limited space, so using a javascript library is out of the question.

Example html:

<form>
    <input type="text" name="field1" value="value1" />
    <input type="text" name="field2" value="value2" />
    <select name="field3">
        <option value="option1" select>Option 1</option>
        <option value="option2" select>Option 2</option>
    </select>
    <input type="Submit" />
</form>

To be clear, inputs that the user does not change should not show up in the POST request when the form is submitted.

like image 338
waldol1 Avatar asked Dec 08 '25 10:12

waldol1


1 Answers

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:

<form onSubmit="beforeSubmit()">
    <input type="text" name="field1" value="value1" onchange="add('field1')" />
    <input type="text" name="field2" value="value2" onchange="add('field2')" />
    <select name="field3" onchange="add('field3')">
        <option value="option1" select>Option 1</option>
        <option value="option2" select>Option 2</option>
    </select>
    <input type="Submit" />
</form>

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

like image 124
waldol1 Avatar answered Dec 10 '25 00:12

waldol1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!