简体   繁体   English

创建动态字段并在其中填充数据

[英]creating dynamic fields and fill the data in it

I have below JSON data and HTML form, in which dynamically fields get created. 我下面有JSON数据和HTML表单,在其中动态创建字段。 This form work to send the data. 该表格负责发送数据。 But how to fill the fields by dynamically creating them 但是如何通过动态创建字段来填充字段

json data json资料

$data = {"1":"a","3":"b","5":"c","2":"d","4":"e"}

index.php 的index.php

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <script type="text/javascript" src="http://code.jquery.com/jquery-compat-git.js"></script>

    <title>Add/Remove Input Fields Dynamically with jQuery</title>
    <script type="text/javascript">
        $(function() {
            $('.multi-field-wrapper').each(function() {
                var $wrapper = $('.multi-fields', this);
                $(".add-field", $(this)).click(function(e) {
                    $('.multi-field:first-child', $wrapper).clone(true).appendTo($wrapper).find('input').val('').focus();
                });
                $('.multi-field .remove-field', $wrapper).click(function() {
                    if ($('.multi-field', $wrapper).length > 1)
                        $(this).parent('.multi-field').remove();
                });
            });
        });
    </script>

</head>

<body>
    <form role="form" action="" method="POST">
        <label>Stuff</label>
        <div class="multi-field-wrapper">
            <div class="multi-fields">
                <div class="multi-field">
                    <select name="id[]">
                        <option value="1">1</option>
                        <option value="2">2</option>
                        <option value="3">3</option>
                        <option value="4">4</option>
                        <option value="5">5</option>
                    </select>
                    <input type="text" name="stuff[]">
                    <button type="button" class="remove-field">Remove</button>
                </div>
            </div>
            <button type="button" class="add-field">Add field</button>
        </div>
        <input type="submit">
    </form>
</body>

</html>

Any help will be appreciated. 任何帮助将不胜感激。

You need a loop. 您需要一个循环。 In javascript you do something like: 在javascript中,您可以执行以下操作:

var $data = {"1":"a","3":"b","5":"c","2":"d","4":"e"};
var formHTML = "";
$.each($data, function(key, value) { 
    var inputHTML = "<input name='"+key+"' value='"+value+"' type="text"/>\n";
    formHTML += inputHTML;
});

And then append formHTML inside your form. 然后在表单中附加formHTML。

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

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