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

标签 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--;
    })
});

Onlick

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

最佳答案

不完全是对您问题的回答,而是对您可以 做什么的建议。

先决条件:test.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>

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>

(让它“易于理解”有点冗长。而且......这只是一个例子。有些东西可能更漂亮,更健壮等)

关于javascript - 如何将动态添加的输入字段关联到父元素/id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35682841/

相关文章:

javascript - Oracle ApEx复选框可在选中/未选中时操纵其他值

php - Webhook 使用 Woocommerce 产品详细信息触发计费程序中的产品插入

arrays - 从文件读取数组

java - 将数组用作变量时未获取完整数组

javascript - 如何控制台数组中大写的日志元素

javascript - jQuery 1.10.2 选择器在 IE 中损坏了吗?

javascript - 如何做出效果?

php - 外键、连接和返回索引

php - Mysql按年分页获取数据

javascript - 发送请求后关闭用 javascript 打开的窗口