How to add a new hidden input fields to the form on submit

The document.forms object is a collection of all <form> elements in the page. It has numeric indexes, and named items. The named items correspond to a name attribute of each <form>.

var theForm = document.forms['detParameterForm'];

To make appending data easier, you can create a function which adds data for a given form.

function addHidden(theForm, key, value) {
    // Create a hidden input element, and append it to the form:
    var input = document.createElement('input');
    input.type="hidden";
    input.name = key; // 'the key/name of the attribute/field that is sent to the server
    input.value = value;
    theForm.appendChild(input);
}

// Form reference:
var theForm = document.forms['detParameterForm'];

// Add data:
addHidden(theForm, 'key-one', 'value');
addHidden(theForm, 'another', 'meow');
addHidden(theForm, 'foobarz', 'baws');

// Submit the form:
theForm.submit();

Leave a Comment