从动态生成的HTML表单中检索字段


Retrieve field from dynamically generated HTML form

我有一个表单,允许用户使用JQuery动态克隆一些字段(例如,请参阅此处)。

<form  name="add_treatment" method="post" action="<?php echo thisURL() ?>">
     <fieldset>
       <legend>Choose treatment</legend> 
       <select id="treatment_id" name="treatment">
           <option>1</option>
           <option>2</option>
           <option>3</option>
       </select>
    </fieldset>
    <fieldset id="event-set">
       <legend>Event</legend>    
       Start <input type="number" name="start"><br>
       End <input type="number" name="end">
    </fieldset>
    <div id="newFields"></div>
    <input type="button" value="+ Add event" id="addInputs" style="width: 20%"/><br><hr>
    <input type="submit" value="Display">
</form>
<script type="text/javascript">
    $('#addInputs').click(function() {
        $('#event-set').clone().appendTo('#newFields');    
    }); 
</script>

该表单用于通过"post"方法显示数据。不同字段的名称属性用于从POST方法中提取它们。所以我在脚本的开头有这样的代码:

<?php if($_POST){
 echo $_POST['treatment'];
 echo $_POST['start'];
 echo $_POST['end'];
} ?> 

问题是,当我复制某些字段时,所有字段都具有相同的name属性。有没有一种方法可以检索所有具有相同名称的字段,或者区分它们?

提前谢谢。

使用:

    Start <input type="number" name="start[]"><br>
    End <input type="number" name="end[]">

而不是:

    Start <input type="number" name="start"><br>
    End <input type="number" name="end">

则在$_POST[‘start’]和$_POSD[‘end’]中会有一个数组。

请参阅:PHP 中的数组发布

您可以获得所有名为"start"的输入,如

$("input[name='start']")

使用:

Start <input type="number" name="start[]"><br>
End <input type="number" name="end[]">

而不是:

Start <input type="number" name="start"><br>
End <input type="number" name="end">

更新代码