简体   繁体   English

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

[英]Retrieve field from dynamically generated HTML form

I have a form in which I allow the user to dynamically clone some fields using JQuery (see here for example ). 我有一个表单,允许用户使用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>

The form is used to display data through a "post" method. 该表格用于通过“发布”方法显示数据。 The name attributes of the different fields are used to extract them from the POST method. 不同字段的名称属性用于从POST方法中提取它们。 So I have this code at the beginning of the script: 所以我在脚本的开头有以下代码:

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

The problem, when I duplicate some of the fields, the all have the same name attribute. 问题是,当我复制某些字段时,所有字段都具有相同的name属性。 Is there a way to retrieve all the fields with the same name, or to differentiate them? 有没有办法检索具有相同名称的所有字段,或区分它们?

Thanks in advance. 提前致谢。

Use: 采用:

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

instead of: 代替:

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

then you will have an array in $_POST['start'] and $_POST['end']. 那么您将在$ _POST ['start']和$ _POST ['end']中创建一个数组。

See: Array posting in PHP 请参阅: PHP中的数组发布

您可以像这样获得所有名为“ start”的输入

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

Use: 采用:

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

instead of: 代替:

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

updated code 更新的代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM