dynamically creating form rows
by snowMonkey
HTML
<form>
<fieldset style=" margin: 0 0 5px 0;">
<div class="container">
</div>
<input value="Add row" type="button" class="add-row-btn">
<input class="button" id="submitBtn" style="margin-left: 85%;" type="button" value="Submit">
</fieldset>
</form>
CSS
.line-title {
width: 200px;
margin: 0px;
height: 15px;
clear: left;
}
.line-number {
width: 45px;
}
.container {
margin: 10px;
}
JavaScript
$(function() {
var rowContents = [];
/******
* Handler for the submit button. I'm doing two things here now -- first, I
* simply dump the contents of the rowContents array. Second, I keep the
* existing handling. Both return the same results, as I've wired the form
* elements to update the rowContents array as they change.
******/
$("#submitBtn").on("click", function() {
console.log("The contents of the rowContents array:");
console.log(JSON.stringify(rowContents) );
console.log("The contents of the actual elements,via the submitted function:");
submitted();
});
// Created an 'add new row' button, which non-destructively adds
// a row to the container.
$(".add-row-btn").on("click", function() {
// createNewRow has to be aware of the rowContents array, as we
// need to create a new element in that array for this row.
$(".container").append(createNewRow(rowContents));
});
// Created a button to delete the chosen row. This should
// remove the row, and remove the row's object in the rowContents
// array.
$("body").on("click", ".del-row-btn", function(event) {
// First, we get the clicked row's index, and use that to remove
// that row from the rowContents array.
var rowToRemove = $(event.currentTarget).parents(".row");
rowIndexToRemove = $(rowToRemove).index();
rowContents.splice(rowIndexToRemove, 1);
// Then, we simply call removeRow and pass it the row to remove.
removeRow(rowToRemove);
});
/******
* Any time the row's text inputs change, I want to update the
* rowContents object. I was using the change event, but the
* issue with that is, if you have a text field highlighted
* and click on submit, it doesn't register the change. This
* way is a little more processor-intensive, but it will work.
*****/
$("body").on("keyup", ".row input", function(event) {
// get the current row
var rowToUpdate =...