如何将动态添加的输入字段与父元素/ id相关联?

时间:2016-02-28 13:00:33

标签: javascript php arrays

我使用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();
});
};

1 个答案:

答案 0 :(得分:1)

不完全是您的问题的答案,但建议您可以做什么。

先决条件:test.php

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

当您提供输入控件时,包含[...] php的名称会将数据视为数组。 E.g。

<!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>

test.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][]

告诉hte php脚本它应该用于药品,哪一个(145),它应该添加一些东西加上[]所以你可以添加(几乎)任意数量的物品。
所以像

这样的POST机构
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>

(保持它“可理解”有点冗长。而且......这只是一个例子。有些东西可能更漂亮,更强大等等)

相关问题