如何将动态添加的输入字段关联到父元素/ID


How to associate dynamically added input fields to parent element/id?

我使用bootstrap和jquery设计了一个用户数据库系统。问题是,每当按下按钮时,它都会附加一个附加字段供用户键入。

假设字段的第一个数组的数组名称为 ref_title[0]按下追加按钮后,将显示另一个具有相同属性的文本字段,但数组值将ref_title[1]

但是在代码本身上,它只会显示ref_title[].这没关系,因为任何新字段都会不断添加到数组ref_title[] 中。我说的对吗?

接下来,单击"保存更改"按钮时,我将使用onclick="newdata('<?php echo $row['drug_id']; ?>')"将数据定向到JS。

'drug_id'是唯一的数字,例如 1、2 或 3。

当我检查第一个框的输入字段时是

<input class="form-control" id="ref_title3" name="ref_title[]" placeholder="Reference Title" type="text">

但是在第二个框上(按下附加按钮并出现附加框后)

<input class="form-control" id="ref_title" name="ref_title[]" placeholder="Reference Title" type="text">

看看id="ref_title".值 3 不回显。

.HTML:

<input type="text" class="form-control" id="ref_title<?php echo $row['drug_id'];?>" name="ref_title[]" placeholder="Reference Title">
<button type="button" onclick="newdata('<?php echo $row['drug_id']; ?>')" class="btn btn-primary" data-dismiss="modal">Save changes</button>

.JS:

$(document).ready(function() {
    var max_fields      = 10; //maximum input boxes allowed
    var wrapper         = $(".input_fields_wrap"); //Fields wrapper
    var add_button      = $(".add_field_button"); //Add button ID
    var x = 1; //initlal text box count
    $(add_button).click(function(e){ //on add input button click
        e.preventDefault();
        if(x < max_fields){ //max input box allowed
            x++; //text box increment
            $(wrapper).append('<div><input type="text" class="form-control" id="ref_title<?php echo $row['drug_id'];?>" name="ref_title[]" placeholder="Reference Title"/></div>"><a href="#" class="remove_field">Remove</a></div>'); //add input box         
        }
    });
    $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
        e.preventDefault(); $(this).parent('div').remove(); x--;
    })
});

昂利克

function newdata(str){
var ref = $('#ref_title'+str).val(); // !!Only can read the first array 
var datas="&ref="+ref;
$.ajax({
   type: "POST",
   url: "update.php",
   data: datas
}).done(function( data ) {
  $('#info').html(data);
  viewdata();
});
};

不完全是你问题的答案,而是关于你能做什么的建议。

先决条件:测试.php

<pre><?php var_export($_POST); ?></pre>

当你给输入控件一个包含[...] php 的名称时,它会将数据视为数组。 例如

<!DOCTYPE html>
<html>
    <head>
        <title>...</title>
        <meta charset="utf-8" />
    </head>
    <body>
        <form method="post" action="test.php">
            <input type="hidden" name="foo[a]" value="a" />
            <input type="hidden" name="foo[b]" value="b" />
            <input type="hidden" name="foo[bar][]" value="bar1" />
            <input type="hidden" name="foo[bar][]" value="bar2" />
            <input type="hidden" name="foo[bar][]" value="bar3" />
            <div>
                <input type="submit" />
            </div>
        </form>
    </body>
</html>

测试的输出.php将是

<pre>array (
  'foo' => 
  array (
    'a' => 'a',
    'b' => 'b',
    'bar' => 
    array (
      0 => 'bar1',
      1 => 'bar2',
      2 => 'bar3',
    ),
  ),
)</pre>

即名称

name="foo[a]"
name="foo[b]"
name="foo[bar][]"
name="foo[bar][]"
name="foo[bar][]"

导致 PHP 构建_POST数组,如下所示

$_POST = array();
$_POST['foo']['a'] = 'a';
$_POST['foo']['b'] = 'b';
// $_POST['foo'][bar] = array()
$_POST['foo']['bar'][] = 'bar1';
$_POST['foo']['bar'][] = 'bar2';
$_POST['foo']['bar'][] = 'bar3';

现在,我建议您像这样构建输入控件的名称:

[drugs][145][add][]

告诉 PHP 脚本它应该处理毒品项目,哪一个 (145),它应该添加一些东西加上 [],这样你就可以添加(几乎)任意数量的项目。
所以像这样的开机自检体

drugs[145][add][]=drug145.1&drugs[145][add][]=drug145.2&drugs[22][add][]=drug22.1
(是的,

是的,编码已关闭...

将导致

_POST==$_POST = array(
    'drugs' = >array(
        '145' => array(
            'add' => array(
                'drug145.1',
                'drug145.2'
            ),
        '22' => array(
            'add' => 'drug22.1'
        )
    )
);

告诉您的 PHP 脚本将drug145.1drug145.2两个描述添加/附加到项目 145 和 drug22.1 添加到项目 22。

这里有一个如何使用html/javascript/jquery执行此操作的示例。

<!DOCTYPE html>
<html>
    <head>
        <title>...</title>
        <meta charset="utf-8" />
        <style type="text/css">
            .adddrugdesc {
                margin-left: 1em;
                cursor: pointer;
                background-color: Cornsilk;
                border: 1px solid silver;
            }
        </style>
    </head>
    <body>
        <form method="post" action="test.php">
            <div class="druglist">      
                <!-- note the drugid as an data-* attribute, see e.g. https://developer.mozilla.org/en/docs/Web/Guide/HTML/Using_data_attributes
                Your php script is supposed to output this id when serving the html document
                -->
                <fieldset><legend data-drugid="3">Drug A</legend></fieldset>
                <fieldset><legend data-drugid="7">Drug B</legend></fieldset>
                <fieldset><legend data-drugid="145">Drug C</legend></fieldset>
                <fieldset><legend data-drugid="22">Drug D</legend></fieldset>
            </div>
            <input type="submit" />
        </form>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
        <script>
            $(document).ready(function() {
                var dl = $(".druglist");
                // add some kind of edit/add button to each fieldset/legend 
                dl.find("fieldset legend").each(function(x) {
                    $(this).append('<span class="adddrugdesc">add description</span>');
                });
                // add an event handler for all edit/add buttons
                dl.on('click', '.adddrugdesc', function(e) {
                    var me = $(this); // this will be the span element the usr clicked on
                    var legend = me.parent('legend'); // this will be the legend element in which the span is located
                    var fset = legend.parent('fieldset'); // same as with legend
                    var drugid = legend.data()['drugid']; // access the data-* attribute of the element via data() and pick the element "drugid"
                    var newinput = $('<input type="text" />');
                    newinput.attr("name", "drugs["+drugid+"][add][]");
                    fset.append(newinput);
                });
            });
        </script>
    </body>
</html>

(保持"可理解"有点冗长。和。。。这只是一个例子。有些东西可能更漂亮,更健壮等)