Jquery克隆表单字段并插入来自db的相应数据

时间:2015-09-29 14:29:21

标签: jquery

在我的联系页面中,我使用克隆功能复制表单的行

<div class="container">
    <div class="row">
        <div class="col-md-12">
            <span id="cloneRowTest" class="label label-primary pointer">
                Add <span class="glyphicon glyphicon-plus"></span>
            </span>
        </div>
    </div>
    <!-- ROW 5 CLONABLE-ROW-LABEL -->
    <div class="row cust-gutters clonable-row-label hidden">
        <div class="col-md-2">
            <label class="control-label" for="mansione">Name</label>
        </div>
        <div class="col-md-3">
            <label class="control-label" for="nominativo">Phone</label>
        </div>
        <div class="col-md-2">
            <label class="control-label" for="telefono">Email</label>
        </div>
    </div>
    <!-- ROW 5 CLONABLE-ROW -->
    <div class="row cust-gutters clonable-row hidden">
        <div class="col-md-2">
            <input type="text" class="form-control input-sm" name="contacts[name][]" placeholder="..." />
        </div>
        <div class="col-md-3">
            <input type="text" class="form-control input-sm" name="contacts[phone][]" placeholder="..." />
        </div>
        <div class="col-md-2">
            <input type="text" class="form-control input-sm" name="contacts[email][]" placeholder="..." />
        </div>
    </div>
</div>

$('#cloneRowTest').on('click', function() {
    var num = $('.clonable-row').length;
    if($('.clonable-row:first').hasClass('hidden')) {
        $('.clonable-row:first, .clonable-row-label').fadeToggle(0).toggleClass('hidden');
    } else {
        if(num < 4) {
            $('.clonable-row:first').clone(true).hide().insertAfter('.clonable-row:last').fadeIn(0);
            $('.clonable-row:last').find('input').each(function() {
                $(this).val('');
            });
        }
    }
});

Bootply

现在我想创建一个“编辑”页面(具有相同的功能),并希望生成行和 插入从db获取的相应值,但我有几个问题。

我的ajax对象响应

data = [
    Object { name="Foo",  phone=87654321,  email="foo@email.com"},
    Object { name="Bar",  phone=12345678,  email="bar@yahoo.com"}
]

克隆行代码并插入相应数据

$.each(data, function(idx, obj) {
    $('#cloneRowTest').trigger('click');
    //alert(); // With this alert are cloned the correct number of rows!  (timeout problem?)
    $.each(obj, function(k, v) {
        $('input[name="contacts[' + k + '][]"]').val(v);
    });
});
  1. 仅创建一行(应为2)
  2. 当我可以克隆正确的行时,行的所有字段都是相同的(数据对象的最后一行)
  3. 我怎么能这样做? 谢谢

0 个答案:

没有答案