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?