How to add values from multiple HTML forms to one

2019-09-10 15:37发布

问题:

I'm building a mobile web application with which employees can submit their worked hours for a given week. The form shows 7 forms (each form represents a day), and is built by a php loop function which runs an array containing information from the week. Each day is a different form.

I cannot combine all days into one, because I need to allow employees to add fields to each day (form in div) themselves to add activities they performed while working.

It looks like this:

If i combine all the days into one form, each time you add a field on a certain day, it adds the field to the first day (while you may need it on the last day).

The Question

I need to submit the entire week using one button. I have already seen javascript methods like

document.getElementById("form1").submit();
document.getElementById("form2").submit();

But this does not work properly. Can anyone provide me with a direction or some code which helps me to solve this? Any help would be highly appreciated!

回答1:

Can you not just achieve this with one form?

HTML

<form>
    <fieldset>
        <!-- all your fields for the day -->
        <legend>Monday</legend>
    </fieldset>

    <fieldset>
        <!-- all your fields for the day -->
        <legend>Tuesday</legend>
    </fieldset>
    <!-- ... -->

    <input type="submit" />        
</form>


回答2:

Looking at the tags that you have added to the question, I assume that you use PHP on the server side. In this case I would use arrays for your input field names:

<form method="post">
    <fieldset>
        <legend>Maandag</legend>
        <input type="text" name="days[maandag][verantwoording][klant][]"><br>
        <input type="text" name="days[maandag][verantwoording][klant][]"><br>
        <input type="text" name="days[maandag][verantwoording][klant][]">
    </fieldset>
    <fieldset>
        <legend>Dinsdag</legend>
        <input type="text" name="days[dinsdag][verantwoording][klant][]"><br>
        <input type="text" name="days[dinsdag][verantwoording][klant][]"><br>
        <input type="text" name="days[dinsdag][verantwoording][klant][]">
    </fieldset>
    <button type="submit">
</form>

Then it is easy to access all of the fields in PHP because PHP will add an (zero-based) index to each of the []:

<?php

echo $_POST['days']['maandag']['verantwoording']['klant'][0];
echo $_POST['days']['maandag']['verantwoording']['klant'][1];
echo $_POST['days']['maandag']['verantwoording']['klant'][2];

See also the documentation on HTML forms