简体   繁体   English

创建动态表单元素,如何保存它们及其状态?

[英]Creating dynamic form elements, how to save them and their state?

I'm fairly new with trying to work with JavaScript and data structures, and in trying to learn, I've created a demo: http://codepen.io/anon/pen/avwZaP 我对尝试使用JavaScript和数据结构还很陌生,并且在尝试学习时,我创建了一个演示: http : //codepen.io/anon/pen/avwZaP

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
</head>
<body>
    <div id="checkList">
        <div class="form-inline checkListItem"><input type="checkbox" id="chk1" /><input type="text" class="form-control" placeholder="Enter checklist item" /></div>
    </div>

    <button id="addCheckbox" class="btn btn-default">Add another item</button>
    <button id="saveData" class="btn btn-primary">Save</button>

    <!--JS-->
    <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

    <script>
        $(document).ready(function () {
            var checkCount = 1;
            $("#addCheckbox").click(function (e) {
                e.preventDefault();
                checkCount++;
                $("#checkList").append('<div class="form-inline"><input type="checkbox" id="chk' + checkCount + '" /> <input type="text" placeholder="Enter checklist item" class="form-control"/> <a href="#" id="removeCheckbox">Remove</a></div>');
            });

            $("#checkList").on("click", "#removeCheckbox", function (e) { 
                e.preventDefault();
                $(this).parent('div').remove();
                checkCount--;
            })
        });

    </script>
</body>
</html>

In the demo, I have a simple check box and a textbox, along with 2 buttons. 在演示中,我有一个简单的复选框和一个文本框,以及2个按钮。 One button dynamically generates another check box and textbox, along with a link to remove it. 一个按钮动态生成另一个复选框和文本框,以及将其删除的链接。 Clicking this button will allow you to add as many as you like. 单击此按钮将允许您添加任意数量的内容。 I also have a save button, which right now does nothing. 我也有一个保存按钮,该按钮现在什么也不做。

What I'd like to do is be able to add as many check boxes/text boxes as I want, be able to fill them out and check them, and then upon clicking save, save everything that is on the page (the n umber of check boxes/text boxes and their state/value). 我想做的就是能够添加任意数量的复选框/文本框,能够填写并选中它们,然后单击“保存”,保存页面上的所有内容(数字)复选框/文本框及其状态/值)。 This is where I'm in over my head and an trying to figure out how to do this. 这是我的头脑,试图弄清楚该怎么做。

I would think that I would need an array of objects...the object being a "checklist" for example, that has a check box and a text box, and the values of each, and then I would store each object in the array. 我认为我需要一个对象数组……例如,该对象是一个“清单”,它具有一个复选框和一个文本框,以及每个对象的值,然后将每个对象存储在数组中。 This is where I'm falling down though, I'm not exactly sure how to do that. 虽然这是我倒下的地方,但我不确定该怎么做。 How do I loop through the dynamically added form elements? 如何遍历动态添加的表单元素? How do I go about saving them in a JavaScript data structure? 如何将它们保存在JavaScript数据结构中?

Your theory is right. 你的理论是对的。 You'll want to loop through each div that's been added to your container ( #checklist ), and have an array of objects. 您将要遍历已添加到容器中的每个div#checklist ),并具有一个对象数组。 Each object should store the values for that row. 每个对象应存储该行的值。

Here's a snippet that does what you're looking for - I've commented what each line is doing. 以下代码片段可以满足您的需求-我已评论了每一行的内容。 HTH! HTH!

$('#saveData').click(function(){        // when we click the save button
    var data = [];                      // create a new array to store stuff
    var $rows = $('#checkList > div');  // get a list of the children div's that have been added
    $rows.each(function(){              // for each of those rows...
        var $rowCheckbox = $(this).find('input[type="checkbox"]');    // get a reference to the checkbox in the row 
        var $rowTextbox = $(this).find('input[type="text"]');         // get a reference to the textbox in the row
        var rowData = {};                               // create a new object for the row
        rowData.id = $rowCheckbox[0].id;                // get the id of the checkbox
        rowData.value = $rowTextbox.val();              // get the value of the textbox
        rowData.checked = $rowCheckbox.is(':checked');  // is the checkbox checked?
        data.push(rowData);                             // add object to array
    });
    console.log(data);        // result
});

Here's an updated CodePen. 这是更新的CodePen。

Here is the Demo . 这是演示 Hope this is what you need. 希望这是您所需要的。 I am creating an array having different json object for each set of checkbox and text. 我正在为每个复选框和文本集创建一个具有不同json对象的数组。

HTML 的HTML

<div id="checkList">
        <div class="form-inline checkListItem"><input type="checkbox" id="chk1" /><input type="text" class="form-control" placeholder="Enter checklist item" /></div>
    </div>

    <button id="addCheckbox" class="btn btn-default">Add another item</button>
    <button id="saveData" class="btn btn-primary">Save</button>

JS JS

$(document).ready(function () {
            var checkCount = 1;
            $("#addCheckbox").click(function (e) {
                e.preventDefault();
                checkCount++;
                $("#checkList").append('<div class="form-inline"><input type="checkbox" id="chk' + checkCount + '" /> <input type="text" placeholder="Enter checklist item" class="form-control"/> <a href="#" id="removeCheckbox">Remove</a></div>');
            });

            $("#checkList").on("click", "#removeCheckbox", function (e) { 
                e.preventDefault();
                $(this).parent('div').remove();
                checkCount--;
            });

            $("#saveData").click(function (e) {
                var resultArray = [];
                $('#checkList').find('div.form-inline').each(function() {
                    var rowData = {};
                    rowData['checkbox'] = $(this).find('input[type=checkbox]').val();
                    rowData['input'] = $(this).find('input[type=text]').val();
                    rowData['checkboxID'] = $(this).find('input[type=checkbox]').attr('id');
                    resultArray.push(rowData);
                });
                console.log(resultArray);
            });
        });

Hope this is what you need! 希望这就是您所需要的!

please check what I edit on your code Solution 请检查什么,我对你的代码编辑解决方案

<div id="checkList">
        <div class="form-inline checkListItem"><input type="checkbox" id="chk1" name="group[][chk]" /><input type="text" name="group[][txt]" class="form-control" placeholder="Enter checklist item" /></div>
    </div>

$(document).ready(function () {
          $("#saveData").click(function(){console.log($("#test").serializeArray())});
            var checkCount = 1;
            $("#addCheckbox").click(function (e) {
                e.preventDefault();
                checkCount++;
                $("#checkList").append('<div class="form-inline"><input type="checkbox" name="group[][chk]" id="chk' + checkCount + '" /> <input type="text"  name="group[][txt]" placeholder="Enter checklist item" class="form-control"/> <a href="#" id="removeCheckbox">Remove</a></div>');
            });

            $("#checkList").on("click", "#removeCheckbox", function (e) { 
                e.preventDefault();
                $(this).parent('div').remove();
                checkCount--;
            })
        });

Well i would rather suggest that instead of looping, you can create form and in that add/remove the fields dynamically. 好吧,我宁愿建议您不要创建循环,而可以创建form并在其中动态添加/删除字段。 On click/submit of that form you can serialize whole form and can submit via ajax, if do not want to reload the page. 在单击/提交该form ,如果不想重新加载页面,则可以serialize整个表单并可以通过ajax提交。

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

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