I dynamically append rows into a table using javascript functions.
Add row function:
function addrow(tableid) {
var tablename = document.getElementById(tableid);
var rows = tablename.rows.length;
if (rows < 8) { //Maximum number of rows allowed
var newrow = tablename.insertRow(rows);
var col = tablename.rows[0].cells.length;
for (var i=0; i<col; i++) {
var newcell = newrow.insertCell(i);
newcell.innerHTML = tablename.rows[0].cells[i].innerHTML;
}
}
else {
alert(" Maximum number of rows allowed is 8");
}
}
HTML Code (row structure) :
<tr>
<p>
<td width="20%">
<input class="input-group-lg" type="text" name="c_degree[]" style="width:90%"/>
</td>
<td width="25%">
<input class="input-group-lg" type="text" name="c_specialization[]" style="width:90%" />
</td>
<td width="30%">
<input class="input-group-lg" type="text" name="c_university[]" style="width:90%" />
</td>
<td width="15%">
<input class="input-group-lg" type="number" name="c_year[]" min="1990" max="2015" />
</td>
<td width="10%">
<input class="input-group-lg" type="number" name="c_marks[]" min="1" max="100" />
</td>
</p>
</tr>
I need to pass data(these arrays) from all the dynamically created rows to an ajax script(which delivers it to the back end).
While using jQuery would make it easy to fetch data from a form with $.serialize(), you've got to do some work without a library. Let's make our own serialize()
function, which we can use like this:
var myFormData = serialize( "myForm" ); // returns an object
Note that "myForm"
could be replaced by any container, even "myTable"
.
Here is a try:
function serialize(formID) {
// New object you'll be building upon
var obj = {},
// Other variables we're going to use
i,l,n,isArray,isNum,val;
// Your form's inputs
var inputs = document.getElementById(formID).getElementsByTagName('input');
// For each of them
for (i = 0, l = inputs.length; i < l; i++) {
// Get their name
n = inputs[i].getAttribute('name');
// Is it an array?
isArray = n.slice(-2) == '[]';
// Is is of type "number"?
isNum = inputs[i].getAttribute('type') == 'number';
// What's the value?
val = inputs[i].value;
// If it's an array
if (isArray) {
// Get rid of the "[]"
n = n.substring(0, n.length - 2);
// If it's the first entry, create an empty array
if (obj[n] === undefined) obj[n] = [];
// Push the value in it (parsed as an integer if it's a number)
obj[n].push(isNum ? +val : val);
// If it's a single field, just assign it
} else obj[n] = isNum ? +val : val;
}
// Return the object
return obj;
}
Note that this function will work with the inputs you provided ("text" & "number"), but would need to be completed to work with other types of inputs, such as radio buttons, select dropdowns, textareas etc. That requires extra work, but if you don't want to reinvent the wheel, you might find a fully working one on the web.