Yarin
Yarin

Reputation: 183519

Form submission of input elements not included in the form

I have an web page where form input elements are in different places and cannot be physically contained within the same form. What's the best approach to include these input values in the form submission?

Note that I want to perform an actual post submission, not an AJAX submission.

Upvotes: 2

Views: 1572

Answers (1)

nnnnnn
nnnnnn

Reputation: 150020

Add an onsubmit handler to the form, and in the handler copy the values from the various inputs to hidden inputs that are in the form.

Note however that this will (obviously) not work for users with JavaScript turned off.

<form id="mainForm" action="yoururl">
   <!-- visible form fields here, then hidden
        fields to hold values from non-form fields -->    

   <input type="hidden" id="field1" name="field1">
   <input type="hidden" id="field2" name="field2">
   <input type="hidden" id="field3" name="field3">
   <input type="hidden" id="field4" name="field4">
</form>

<!-- other fields to be submitted with mainForm -->    
<input type="text" id="displayfield1">
<input type="text" id="displayfield2">
<input type="text" id="displayfield3">
<input type="text" id="displayfield4">

<script>
   document.getElementById("mainForm").onsubmit = function(e) {
       e = e || window.event;
       var theForm = e.target || e.srcElement;

       // could copy fields across manually, one by one:
       document.getElementById("field1").value =
                             document.getElementById("displayField1").value;

       // or you could copy based on matching field ids:
       var fields = theForm.getElementsByTagName("input"),
           i,
           df;

       for (i=0; i < fields.length; i++) {
           if (fields[i].type === "hidden") {
              df = document.getElementById("display" + fields[i].id);
              if (df != null)
                 fields[i].value = df.value;
           }
       }

       // could return false here if there was some failed
       // validation and you wanted to stop the form submitting
       return true;
   };
</script>

Sorry about the somewhat ugly code - just whipped something up off the top of my head. If you're interested you could do all of the above in about three lines of jQuery...

Upvotes: 2

Related Questions