0

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

<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. 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?

JesseEarley
  • 1,036
  • 9
  • 20
  • when you are trying to retrieve back the saved state.?? – Guruprasad J Rao Oct 08 '15 at 12:24
  • At this point I'm not trying to retrieve back the saved state, I'm just trying to figure out how to save the current state. If I can get help on that, I would think I'd be able to figure out how to retrieve the data at that point. – JesseEarley Oct 08 '15 at 12:26
  • See there are many solutions. One would be **[like this](http://codepen.io/kshkrao3/pen/EVXyqM)**.. But this does not work on page reload.. There would be different approach for that.. So I just asked to be clear with your requirements. – Guruprasad J Rao Oct 08 '15 at 12:27

4 Answers4

1

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. 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!

$('#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.

Dave Salomon
  • 3,287
  • 1
  • 17
  • 29
1

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.

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

Hope this is what you need!

Deepak Biswal
  • 4,280
  • 2
  • 20
  • 37
0

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--;
            })
        });
Hamza Alayed
  • 635
  • 5
  • 17
0

Well i would rather suggest that instead of looping, you can create form and in that add/remove the fields dynamically. On click/submit of that form you can serialize whole form and can submit via ajax, if do not want to reload the page.

Harsh Makani
  • 761
  • 5
  • 11
  • I have not used serialize before, how would that work? – JesseEarley Oct 08 '15 at 12:35
  • @JesseEarley have a look at these links : 1) http://devzone.co.in/jquery-serialize-function-ajax-post-bigger-html-forms/ 2) http://stackoverflow.com/questions/24007780/jquery-ajax-form-data-serialize-using-php – Harsh Makani Oct 08 '15 at 12:38