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

时间:2017-02-24 13:39:56

标签: php jquery json

我有以下JSON数据和HTML形式,其中创建了动态字段。此表单用于发送数据。但是如何通过动态创建字段来填充字段

json数据

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

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

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

你需要一个循环。在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;
});

然后在表单中附加formHTML。