簡體   English   中英

創建動態表單元素,如何保存它們及其狀態?

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

我對嘗試使用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>

在演示中,我有一個簡單的復選框和一個文本框,以及2個按鈕。 一個按鈕動態生成另一個復選框和文本框,以及將其刪除的鏈接。 單擊此按鈕將允許您添加任意數量的內容。 我也有一個保存按鈕,該按鈕現在什么也不做。

我想做的就是能夠添加任意數量的復選框/文本框,能夠填寫並選中它們,然后單擊“保存”,保存頁面上的所有內容(數字)復選框/文本框及其狀態/值)。 這是我的頭腦,試圖弄清楚該怎么做。

我認為我需要一個對象數組……例如,該對象是一個“清單”,它具有一個復選框和一個文本框,以及每個對象的值,然后將每個對象存儲在數組中。 雖然這是我倒下的地方,但我不確定該怎么做。 如何遍歷動態添加的表單元素? 如何將它們保存在JavaScript數據結構中?

你的理論是對的。 您將要遍歷已添加到容器中的每個div#checklist ),並具有一個對象數組。 每個對象應存儲該行的值。

以下代碼片段可以滿足您的需求-我已評論了每一行的內容。 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
});

這是更新的CodePen。

這是演示 希望這是您所需要的。 我正在為每個復選框和文本集創建一個具有不同json對象的數組。

的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

$(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);
            });
        });

希望這就是您所需要的!

請檢查什么,我對你的代碼編輯解決方案

<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--;
            })
        });

好吧,我寧願建議您不要創建循環,而可以創建form並在其中動態添加/刪除字段。 在單擊/提交該form ,如果不想重新加載頁面,則可以serialize整個表單並可以通過ajax提交。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM