在将表单数据保存到序列化数组Javascript之后重新填充表单

时间:2016-11-09 22:18:34

标签: javascript jquery html forms

我正在创建一个我希望用户能够编辑的表单。用户将填写表单,保存该表单,填写下一个条目的表单,保存该表单等。每次保存表单时都会创建一个可点击的div,以便用户可以返回并查看他们的输入以确保他们在最终提交所有表格之前是正确的。我已经能够保存表单数据了:

    var formArray = $('form#popsetForm').serializeArray();

我的问题:当用户点击div时,我现在想用formArray中的数据填充表单。是否有一个简单的命令,允许我只提供数组作为输入,它会自动填充表单?以下不是真正的代码,而是我希望存在的。

    $('form#popsetForm').populate(formArray)

2 个答案:

答案 0 :(得分:1)

我不知道解决方案是否已经存在但是这样的事情应该适用于serializeArray

function restoreForm(form, formArray) {
  formArray.forEach(function (pair) {
    var selector = `input[name="${ pair.name }"], textarea[name="${ pair.name }"]`
    var input = $(form).find(selector)
    input.val(pair.value);
  })
}

https://jsfiddle.net/aycnx0gd/4/

或者像常规ol'formData

一样
function restoreForm(form, formData) {
  for (var key of formData.keys()) {
    var selector = `input[name="${ key }"], textarea[name="${ key }"]`
    var input = $(form).find(selector)
    var newVal = formData.get(key)
    input.val(newVal);
  }
}

https://jsfiddle.net/aycnx0gd/2/

答案 1 :(得分:0)

我会考虑将视图隐藏起来,根本不需要重新填充它。

您的表单提交处理程序可能如下所示:

$('#some_common_parent_element_to_all_forms').on('submit', 'form', function() {

    var $currentForm = $(this);

    // not shown - your form submit logic here

    // on success of form submittal execute following...

    // hide submitted form
    $currentForm.hide();

    // was form submitted previously?
    // if so, we don't want to generate a new form
    if($currentForm.data('submitted') !== true) {

        // clone form
        var $newForm = $currentForm.clone();

        // reset cloned form
        $newForm.get(0).reset();

        // mark submitted form as submitted
        $currentForm.data('submitted', true);


        // append new form to DOM
        $('#some_common_parent_element_to_all_forms').append($newForm).show();

        // create new div to be able to "navigate" to submitted form
        var $formNavContainer = $('#some_element_that_holds_nav_divs');
        var currentNavCount =
            $formNavContainer.find('.form_navigation').length;
        var formDisplayNum = currentNavCount + 1;
        var $newNav =
            $('<div class="form_navigation">Form ' + formDisplayNum + '</div>');
        $newNav.data('target-form-index', currentNavCount);
        $newNav.appendTo($formNavContainer);
    } else {
        // this form was previously submitted
        // perhaps we just reveal most recently created form
        $('#some_common_parent_element_to_all_forms form').last().show();
    }
}

导航div的点击处理程序可能如下所示:

$('#some_element_that_holds_nav_divs').on('click', '.form_navigation', function() {
    var $clickedNav = $(this);
    var formIndex = $clickedNav.data('target-form-index');

    var $allForms = $('#some_common_parent_element_to_all_forms form');
    var $selectedForm = $allForms.get(formIndex);

    $allForms.hide();
    $selectedForm.show();
});

这种方法允许您创建X个表单,每个表单都存储自己的表单数据集。 &#34;导航&#34;然后,表单之间只是显示/隐藏单个表单的问题。