accessing values of dynamic table row using javascript - javascript

i am writing a js code for creating a dynamic table with 3 columns per row viz.
textbox1 | textbox2 | textbox3
textbox1 | textbox2 | textbox3
..
what i'm trying to do is take values of textbox1 and textbox2 and show the multiplication result of these values in textbox 3.
but my script ain't working..
Kindly suggest the remedy or a better way to do this ...
code :
function addRowToTable() {
var tbl = document.getElementById('tblSample');
var lastRow = tbl.rows.length;
// if there's no header row in the table, then iteration = lastRow + 1
var iteration = lastRow;
var row = tbl.insertRow(lastRow);
// left cell
var cellLeft = row.insertCell(0);
var textNode = document.createTextNode(iteration);
cellLeft.appendChild(textNode);
var cellRight = row.insertCell(1);
var el = document.createElement('input');
el.setAttribute('type', 'text');
el.setAttribute('id', 'f1' + iteration);
el.setAttribute('size', '22');
cellRight.appendChild(el);
var cellRight = row.insertCell(1);
var el = document.createElement('input');
el.setAttribute('type', 'text');
el.setAttribute('id', 'f2' + iteration);
el.setAttribute('size', '20');
cellRight.appendChild(el);
var cellRight = row.insertCell(1);
var el = document.createElement('input');
el.setAttribute('type', 'text');
el.setAttribute('id', 'f3' + iteration);
el.setAttribute('size', '20');
cellRight.appendChild(el);
}
function removeRowFromTable() {
var tbl = document.getElementById('tblSample');
var lastRow = tbl.rows.length;
if (lastRow > 2) tbl.deleteRow(lastRow - 1);
}
function store3() {
var tbl = document.getElementById('tblSample');
var rowIterator = tbl.rows.length;
var z = document.getElementById("f3");
z.value = (document.getElementById("f1").value) * (document.getElementById("f2").value) * 1;
}
Form goes like this:
<form action="tableaddrow_nw.html" method="get">
<input type="button" value="Add Position" onclick="addRowToTable();" />
<input type="button" value="Remove Position" onclick="removeRowFromTable();" />
<table border="1" id="tblSample">
<tr>
<td><input type="text" name="f1" id="f1" size="20" onkeyup="store3()"/></td>
<td><input type="text" name="f2" id="f2" size="20" onkeyup="store3()"/></td>
<td><input type="text" name="f3" id="f3" size="20" /></td>
</tr>
</table>
</form>

I modified your code, it should multiply when you add new rows,
Here is the Working Demo
HTML
<form action="tableaddrow_nw.html" method="get">
<input type="button" value="Add Position" onclick="addRowToTable();" />
<input type="button" value="Remove Position" onclick="removeRowFromTable();" />
<table border="1" id="tblSample">
<tr>
<td><input type="text" name="f1" id="f1" size="20" onkeyup="store3('f1','f2', 'f3')"/></td>
<td><input type="text" name="f2" id="f2" size="20" onkeyup="store3('f1','f2', 'f3')"/></td>
<td><input type="text" name="f3" id="f3" size="20" /></td>
</tr>
</table>
SCRIPT:
function addRowToTable()
{
var tbl = document.getElementById('tblSample');
var lastRow = tbl.rows.length;
// if there's no header row in the table, then iteration = lastRow + 1
var iteration = lastRow;
var row = tbl.insertRow(lastRow);
// left cell
var cellLeft = row.insertCell(0);
var textNode = document.createTextNode(iteration);
cellLeft.appendChild(textNode);
var cellRight = row.insertCell(1);
var el = document.createElement('input');
el.setAttribute('type', 'text');
el.setAttribute('id', 'f1' + iteration);
el.setAttribute('size', '22');
el.onkeyup = function(){store3('f3' + iteration,'f2' + iteration, 'f1' + iteration)}
cellRight.appendChild(el);
var cellRight = row.insertCell(1);
var el = document.createElement('input');
el.setAttribute('type', 'text');
el.setAttribute('id', 'f2' + iteration);
el.setAttribute('size', '20');
el.onkeyup = function(){store3('f3' + iteration,'f2' + iteration, 'f1' + iteration)}
cellRight.appendChild(el);
var cellRight = row.insertCell(1);
var el = document.createElement('input');
el.setAttribute('type', 'text');
el.setAttribute('id', 'f3' + iteration);
el.setAttribute('size', '20');
el.onkeyup = function(){store3('f3' + iteration,'f2' + iteration, 'f1' + iteration)}
cellRight.appendChild(el);
}
function removeRowFromTable()
{
var tbl = document.getElementById('tblSample');
var lastRow = tbl.rows.length;
if (lastRow > 2) tbl.deleteRow(lastRow - 1);
}
function store3(t1, t2, t3)
{
var tbl = document.getElementById('tblSample');
var rowIterator = tbl.rows.length;
var z=document.getElementById(t3);
z.value=(document.getElementById(t1).value)*(document.getElementById(t2).value)*1;
}

Your JavaScript code refers to hard-coded element ids, so it will NEVER work with any other ids as it is.
I suggest you use the same naming convention for your existing row(s) as for the ones that you create in your script. Also give an id to each of the rows and pass that id to your store3() function [you should really call it something like calculateSum() or something similar, it is always better to have meaningful names] - then you can work out dynamic ids for each of the fields from the id passed to the function.

Related

websql add button to insert new values in table

I am a newbie and i need help, it is to complex for me.
Sorry for my bad englisch.
I have this cool Code from #rushi and now i need a button to insert and to update a change and send it back into the table.
On the page it looks nice, there is a button on the end of the table-view and the input type = text has the right value from the table connect (see picture)!
The original code block from rushi u find here -> web-sql, javascript, show all tables of database
This is the code in the moment.
Can u help me to find the solution for the "update-button"?
function processResultSet(tblname,results) {
console.log('----------------------'+tblname)
var len = results.rows.length;
var tbl = document.createElement('table');
var trTblName = document.createElement('tr');
var thTblName = document.createElement('th');
thTblName.innerHTML = tblname;
trTblName.colSpan = 2;
trTblName.appendChild(thTblName);
tbl.appendChild(trTblName);
//create Table-Head
var trHeader = document.createElement('tr');
var th1 = document.createElement('th');
th1.innerHTML = '<font color=orange> ID STEMPEL</font>';
var th2 = document.createElement('th');
th2.innerHTML = '<font color=red> HERSTELLER </font>';
var th3 = document.createElement('th');
th3.innerHTML = '<font color=green> STÜCKZAHL </font>';
var th4 = document.createElement('th');
th4.innerHTML = '<font color=blue> KALIBER </font>';
trHeader.appendChild(th1);
trHeader.appendChild(th2);
trHeader.appendChild(th3);
trHeader.appendChild(th4);
tbl.appendChild(trHeader);
//create Table-Inserts, show what is in the table
for (var i = 0; i < len; i++) {
var tr = document.createElement('tr');
var td1 = document.createElement('td');
td1.innerHTML = results.rows[i].id;
var td2 = document.createElement('td');
td2.innerHTML = results.rows[i].hersteller;
var td3 = document.createElement('td');
td3.innerHTML = '<form method="GET" action="edit_munition.html"><input name="formstueckzahl" type="text" value="' + results.rows[i].stueckzahl + '" size="5" maxlength="4" id="' + results.rows[i].id + '">';
var td4 = document.createElement('td');
td4.innerHTML = results.rows[i].kaliber;
var td5 = document.createElement('td');
td5.innerHTML = '<input type="submit" name="form" value="update"></form>';
tr.appendChild(td1);
tr.appendChild(td2);
tr.appendChild(td3);
tr.appendChild(td4);
tr.appendChild(td5);
tbl.appendChild(tr);
}
var body = document.getElementsByTagName('X')[0];
body.appendChild(tbl);
body.appendChild(document.createElement('hr'));
}
Solution:
td3.innerHTML = '<form method="GET" action="edit_munition.html"><input name="formstueckzahl" type="text" value="' + results.rows[i].stueckzahl + '" size="5" maxlength="4" id="formstueckzahl"><input type="hidden" name="formid" value="' + results.rows[i].id + '">' + " " + '<input type="submit" name="form" value="update"></form>';

Script doesn't work after adding row dynamically

I have one function which calculates the total amount.
amount=qty*rate
Here is my html code for showing table
When I add new row it doesn't trigger that calculate function
Can any one help me out?
Here is my script:
function calculate() {
var myBox1 = document.getElementById('qty').value;
var myBox2 = document.getElementById('rate').value;
var amnt = document.getElementById('amnt');
var myResult = myBox1 * myBox2;
amnt.value = myResult;
}
var count = "1";
function addRow(in_tbl_name)
{
var tbody = document.getElementById(in_tbl_name).getElementsByTagName("TBODY")[0];
// create row
var row = document.createElement("TR");
// create table cell 1
var td1 = document.createElement("TD")
var strHtml1 = "<INPUT TYPE=\"text\" NAME=\"r_name\" SIZE=\"30\">";
td1.innerHTML = strHtml1.replace(/!count!/g,count);
// create table cell 2
var td2 = document.createElement("TD")
var strHtml2 = "<INPUT TYPE=\"text\" NAME=\"r_desc\" PLACEHOLDER=\"description\" SIZE=\"30\">";
td2.innerHTML = strHtml2.replace(/!count!/g,count);
// create table cell 3
var td3 = document.createElement("TD")
var strHtml3 = "<INPUT TYPE=\"text\" NAME=\"r_qty\" PLACEHOLDER=\"QTY\" ID=\"qty\" ONINPUT=\"calculate()\" SIZE=\"30\">";
td3.innerHTML = strHtml3.replace(/!count!/g,count);
// create table cell 4
var td4 = document.createElement("TD")
var strHtml4 = "<INPUT TYPE=\"text\" NAME=\"r_RATE\" PLACEHOLDER=\"rate\" ID=\"rate\" ONINPUT=\"calculate()\" SIZE=\"30\">";
td4.innerHTML = strHtml4.replace(/!count!/g,count);
// create table cell 5
var td5 = document.createElement("TD")
var strHtml5 = "<INPUT TYPE=\"text\" NAME=\"r_total\" PLACEHOLDER=\"amount\" ID=\"amnt\" >";
td5.innerHTML = strHtml5.replace(/!count!/g,count);
// create table cell 4
var td6 = document.createElement("TD")
var strHtml6 = "<INPUT TYPE=\"Button\" CLASS=\"Button\" onClick=\"delRow()\" VALUE=\"Delete Row\">";
td6.innerHTML = strHtml6.replace(/!count!/g,count);
// append data to row
row.appendChild(td1);
row.appendChild(td2);
row.appendChild(td3);
row.appendChild(td4);
row.appendChild(td5);
row.appendChild(td6);
// add to count variable
count = parseInt(count) + 1;
// append row to table
tbody.appendChild(row);
}
function delRow()
{
var current = window.event.srcElement;
//here we will delete the line
while ( (current = current.parentElement) && current.tagName !="TR");
current.parentElement.removeChild(current);
}
<TABLE ID="tblPets" border="1" STYLE="border width:1 orange dashed;background color:#F0E68C;table-row width:2;">
<tr>
<th><center>Row material Name</center></th>
<th><center>Description</center></th>
<th><center>Qty.</center></th>
<th><center>Rate</center></th>
<th><center>Amount</center></th>
<th><center><INPUT TYPE="Button" onClick="addRow('tblPets')" VALUE="Add Row"></center></th>
</tr>
<tr>
<th><center><INPUT TYPE="text" NAME="r_name" SIZE="30"></center></th>
<th><center><INPUT TYPE="text" NAME="r_desc" PLACEHOLDER="description" SIZE="30"></center></th>
<th><center><INPUT TYPE="text" NAME="r_qty" PLACEHOLDER="QTY" ID="qty" ONINPUT="calculate()" SIZE="30"></center></th>
<th><center><INPUT TYPE="text" NAME="r_RATE" PLACEHOLDER="rate" ID="rate" ONINPUT="calculate()" SIZE="30"></center></th>
<th><center><INPUT TYPE="text" NAME="r_total" PLACEHOLDER="amount" ID="amnt" ></center></th>
<th><center></center></th>
</tr>
</TABLE>
Here is my HTML code
I understand now what you wanted to do.
You're using the same element id multiple times, so your calculate() function always selects only the first inputs in the first row.
I calculate() so it takes as a parameter the element that triggered the event and then traverses up the DOM tree to find the closest <tr>:
var tr = elm;
while ((tr = tr.parentElement) && tr.tagName !== 'TR');
Then select input fields only in this table row, calculate what you want and set it as a value to another input field in the same row.
Last thing I changes is that I trigger oninput with oninput=calculate(this) where this is the current DOM element.
function calculate(elm) {
var tr = elm;
while ((tr = tr.parentElement) && tr.tagName !== 'TR');
var inputs = tr.querySelectorAll('input');
var myBox1 = inputs[2].value;
var myBox2 = inputs[3].value;
var myResult = myBox1 * myBox2;
inputs[4].value = myResult;
}
var count = "1";
function addRow(in_tbl_name)
{
var tbody = document.getElementById(in_tbl_name).getElementsByTagName("TBODY")[0];
// create row
var row = document.createElement("TR");
// create table cell 1
var td1 = document.createElement("TD")
var strHtml1 = "<INPUT TYPE=\"text\" NAME=\"r_name\" SIZE=\"30\">";
td1.innerHTML = strHtml1.replace(/!count!/g,count);
// create table cell 2
var td2 = document.createElement("TD")
var strHtml2 = "<INPUT TYPE=\"text\" NAME=\"r_desc\" PLACEHOLDER=\"description\" SIZE=\"30\">";
td2.innerHTML = strHtml2.replace(/!count!/g,count);
// create table cell 3
var td3 = document.createElement("TD")
var strHtml3 = "<INPUT TYPE=\"text\" NAME=\"r_qty\" PLACEHOLDER=\"QTY\" ID=\"qty\" ONINPUT=\"calculate(this)\" SIZE=\"30\">";
td3.innerHTML = strHtml3.replace(/!count!/g,count);
// create table cell 4
var td4 = document.createElement("TD")
var strHtml4 = "<INPUT TYPE=\"text\" NAME=\"r_RATE\" PLACEHOLDER=\"rate\" ID=\"rate\" ONINPUT=\"calculate(this)\" SIZE=\"30\">";
td4.innerHTML = strHtml4.replace(/!count!/g,count);
// create table cell 5
var td5 = document.createElement("TD")
var strHtml5 = "<INPUT TYPE=\"text\" NAME=\"r_total\" PLACEHOLDER=\"amount\" ID=\"amnt\" >";
td5.innerHTML = strHtml5.replace(/!count!/g,count);
// create table cell 4
var td6 = document.createElement("TD")
var strHtml6 = "<INPUT TYPE=\"Button\" CLASS=\"Button\" onClick=\"delRow()\" VALUE=\"Delete Row\">";
td6.innerHTML = strHtml6.replace(/!count!/g,count);
// append data to row
row.appendChild(td1);
row.appendChild(td2);
row.appendChild(td3);
row.appendChild(td4);
row.appendChild(td5);
row.appendChild(td6);
// add to count variable
count = parseInt(count) + 1;
// append row to table
tbody.appendChild(row);
}
function delRow()
{
var current = window.event.srcElement;
//here we will delete the line
while ( (current = current.parentElement) && current.tagName !="TR");
current.parentElement.removeChild(current);
}
<TABLE ID="tblPets" border="1" STYLE="border width:1 orange dashed;background color:#F0E68C;table-row width:2;">
<tr>
<th><center>Row material Name</center></th>
<th><center>Description</center></th>
<th><center>Qty.</center></th>
<th><center>Rate</center></th>
<th><center>Amount</center></th>
<th><center><INPUT TYPE="Button" onClick="addRow('tblPets')" VALUE="Add Row"></center></th>
</tr>
<tr>
<th><center><INPUT TYPE="text" NAME="r_name" SIZE="30"></center></th>
<th><center><INPUT TYPE="text" NAME="r_desc" PLACEHOLDER="description" SIZE="30"></center></th>
<th><center><INPUT TYPE="text" NAME="r_qty" PLACEHOLDER="QTY" ID="qty" ONINPUT="calculate(this)" SIZE="30"></center></th>
<th><center><INPUT TYPE="text" NAME="r_RATE" PLACEHOLDER="rate" ID="rate" ONINPUT="calculate(this)" SIZE="30"></center></th>
<th><center><INPUT TYPE="text" NAME="r_total" PLACEHOLDER="amount" ID="amnt" ></center></th>
<th><center></center></th>
</tr>
</TABLE>

increment Calendar date in javascript

I am writing code to add rows dynamically on selecting the month and year. It should display rows of labels with all dates for that month.
I have written code for adding new row on button click and am stuck on adding date to label dynamically
<BODY>
<INPUT type="button" value="Add Row" id="addRow" onclick="addRow('dataTable')" />
<TABLE id="dataTable" width="350px" border="1">
</TABLE>
<%
int year= 2015,month = 10;
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month);
int numDays = calendar.getActualMaximum(Calendar.DATE);
SimpleDateFormat df = new SimpleDateFormat("dd/MMM/yyyy");
calendar.set(Calendar.DAY_OF_MONTH,1);
%>
<SCRIPT language="javascript">
var count=1;
var numDays = "<%=numDays %>";
while(count <= numDays-1 ) {
count++;
// calendar.set(Calendar.DAY_OF_MONTH,count); //error in this part when uncommented
$("#addRow").trigger("click");
}
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
element1.name="chkbox[]";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
cell2.innerHTML = "<%= df.format(calendar.getTime()) %>"; //new date here
var cell3 = row.insertCell(2);
var element2 = document.createElement("input");
element2.type = "text";
element2.name = "txtbox[]";
cell3.appendChild(element2);
}
</SCRIPT>
</BODY>
Not able to use calendar.set(Calendar.DAY_OF_MONTH,count) within the loop, so that date is incremented on each click. When running calendar.set(Calendar.DAY_OF_MONTH,1); it is displaying output as given in image
snapshot of output when setting DAY_OF_MONTH outside the loop
I have found the answer. Actually its a other way workout.
Have fetched the no of days in the calendar (from server date) and run a loop for each count trigger the addrow button incrementing the label value.
JS code =>
numDays = "<%= numDays%>";
while (count <= numDays - 1) {
count = count + 1;
$("#btnAddRow").trigger("click");
}
function addRow(tableID) {
var countCol = parseInt($('#dataTable').attr('data-countCol'), 10) || 1;
countRow = countRow + 1;
var index = $("#dataTable tr:last").attr("id").split("_")[1];
var rid = "r_" + (parseInt(index) + 1);
var tempRow = $("#dataTable tr:last").clone(true, true);
tempRow.attr("id", rid);
var checkCol = $('#dataTable tr:last td:first input');
checkCol.prop("check", true);
checkCol.prop("id", "check-" + index);
var dateCol = $('#dataTable tr:last td:nth-child(2) input');
dateCol.prop("readonly", true);
var pv_dt = dateCol.val().split("/");
pv_dt[0] = parseInt(pv_dt[0]) + 1;
var nw_dt = pv_dt.join("/");
$(tempRow).find('td:nth-child(2) input').val(nw_dt);
tempRow.find('td:nth-child(3) input').prop('name', "rom_" + parseInt(countRow) + "." + countCol);
tempRow.find('td:nth-child(4) input').prop('name', "waste_" + parseInt(countRow) + "." + countCol);
tempRow.find('td:nth-child(5) input').prop('name', "fh_" + parseInt(countRow) + "." + countCol);
tempRow.find('td:nth-child(6) input').prop('name', "ot-rom_" + parseInt(countRow) + "." + countCol);
tempRow.find('td:nth-child(7) input').prop('name', "ot-waste_" + parseInt(countRow) + "." + countCol);
tempRow.find('td:nth-child(8) input').prop('name', "ot-FH_" + parseInt(countRow) + "." + countCol);
$('#dataTable').append(tempRow);
}

Can't Find Dynamically Generated Textboxes

I have two functions - one takes a URL in a certain format (e.g. "test.com?action=query&max_results=20") and breaks it down into dynamically generated textboxes for editing. The other puts it back together along with any edits. Both functions are called by clicking a button.
The second function is unable to find the ids of the dynamically generated textboxes - they're coming back as "null". How do I get the function to recognise ids created after the page loads?
Code:
<script>
function Split()
{
//Get table body for insert
var table = document.getElementById("ValueTableBody");
//Clear table of rows
table.innerHTML = '';
//Grab URL
var URLquery = document.getElementById("oldquery").value;
//Split on ? to isolate query
var querysplit = oldquery.split("?");
//Store main url
var mainURL = document.getElementById('mainURL');
mainURL.value=querysplit[0];
//Split on & to isolate variables
var splitagain = querysplit[1].split("&");
var i = 0;
//Loop on number of variables in query
for(i = 0; i < splitagain.length; i++){
//Split on = to isolate variables and values
var splitthird = splitagain[i].split("=");
//Insert new row into table
var row = table.insertRow(i);
row.insertCell(0).innerHTML = '<input type="text" id="query' + i + '"/>';
row.insertCell(1).innerHTML = '<input size="50" type="text" id="queryvalue' + i + '"/>';
//Insert variable and value into respective inputs.
var split1 = document.getElementById('query' + i);
split1.value=splitthird[0];
var split2 = document.getElementById('queryvalue' + i);
split2.value=splitthird[1];
}
}
function Unsplit()
{
var mainURL = document.getElementById('mainURL').value;
var completequery = [];
var URLarray = [];
var rowCount = document.getElementById('ValueTableBody').rows.length;
for(i = 0; i <= rowCount; i++){
//Get variable of current row
var value1 = document.getElementById('query' + i).value;
//Get value of current row
var value2 = document.getElementById('queryvalue' + i).value;
if (value1) {
if (value2) {
//If both have value, then push into array
valueArray = [];
valueArray.push(value1);
valueArray.push(value2);
//Merge into one to push into next array
var newvalue = valueArray.join("=");
URLarray.push(newvalue);
}
}
}
//Join all sections of the query together
mergearray = URLarray.join("&");
//Push mainURL
completequery.push(mainURL);
//Push completed query
completequery.push(mergearray);
//Join the query together to make complete new URL
mergearray2 = completequery.join("?");
//Display new URL
var newquery = document.getElementById('newquery');
newquery.value=mergearray2;
//Output new URL to iframe
document.getElementById('webservicedisplay').src = mergearray2;
}
</script>
HTML:
<div style="float:left;">
<h1>Webservice Tester</h1>
<p><label style="font-weight:bold; display:inline-block; vertical-align:top;">Old Webservice Call:</label> <textarea cols="60" rows="4" id="oldquery"></textarea></p>
<input type="submit" name="button" id="splitbutton" onclick="Split()" value="Split!" /> <br><br>
<p><label style="font-weight:bold;">URL:</label> <input type="text" size="50" id="mainURL"></input></p><br>
<table id="ValueTable">
<thead>
<th>Variable</th>
<th>Value</th>
</thead>
<tbody id="ValueTableBody">
</tbody>
</table>
<br>
<p><input type="submit" name="button" id="unsplit" onclick="Unsplit()" value="Unsplit!" /></p> <br><br>
<p><label style="font-weight:bold; vertical-align:top;">New Webservice Call:</label> <textarea cols="60" rows="4" id="newquery"></textarea></p>
</div>
<div style="float:left; padding-left:20px;">
<p><label style="font-weight:bold;">Output:</label></p><br>
<iframe height="450" width="500" id="webservicedisplay" src="">
</iframe>
This was fixed by the author because the 'issue was actually the loop having the "<=" condition - it was looking for one more table row that didn't exist.'
I had suggested to write the JS differently as so:
row.insertCell(0).innerHTML = '<input type="text" id="query' + i + '" value="' + splitthird[0] + '"/>';
row.insertCell(1).innerHTML = '<input size="50" type="text" id="queryvalue' + i + '" value="' + splitthird[1] + '"/>';
And remove:
//Insert variable and value into respective inputs.
var split1 = document.getElementById('query' + i);
split1.value=splitthird[0];
var split2 = document.getElementById('queryvalue' + i);
split2.value=splitthird[1];

javascript dynamic input fields

I have a problem with JavaScript dynamic input fields. I have three fields, one with a number and two with a & b. My problem is displaying the b input field under the a input field.
My code:
<script language="JavaScript" type="text/javascript">
function addRowToTable()
{
var tbl = document.getElementById('tblSample');
var lastRow = tbl.rows.length;
// if there's no header row in the table, then iteration = lastRow + 1
var iteration = lastRow;
var row = tbl.insertRow(lastRow);
// left cell
var cellLeft = row.insertCell(0);
var textNode = document.createTextNode(iteration);
cellLeft.appendChild(textNode);
// right cell
var cellRight1 = row.insertCell(1);
var el = document.createElement('input');
el.type = 'text';
el.name = 'element_45_1' + iteration;
el.id = 'element_45_1' + iteration;
el.size = 40;
//el.onkeypress = keyPressTest;
cellRight1.appendChild(el);
// right cell
var cellRight2 = row.insertCell(2);
var el = document.createElement('input');
el.type = 'text';
el.name = 'element_45_2' + iteration;
el.id = 'element_45_2' + iteration;
el.size = 40;
//el.onkeypress = keyPressTest;
cellRight2.appendChild(el);
// right cell
var cellBottom3 = row.insertCell(3);
var el = document.createElement('input');
el.type = 'text';
el.name = 'element_45_12' + iteration;
el.id = 'element_45_12' + iteration;
el.size = 40;
//el.onkeypress = keyPressTest;
cellBottom3.appendChild(el);
}
function removeRowFromTable()
{
var tbl = document.getElementById('tblSample');
var lastRow = tbl.rows.length;
if (lastRow > 2) tbl.deleteRow(lastRow - 1);
}
</script>
<form action="tableaddrow_nw.html" method="get">
<table width="540" border="1" id="tblSample">
<tr>
<th colspan="3">Sample table</th>
</tr>
<tr>
<td width="8">1</td>
<td width="240">
<input type="text" name="element_45_1"
id="element_45_1" size="40" />
</td>
<td width="20">
<div1>
a.
<input type="text" name="element_45_2"
id="element_45_2" size="40" />
</div1>
</td>
<td width="20">
b.
<input type="text" name="element_45_12"
id="element_45_12" size="40" />
</td>
</tr>
</table>
</form>
<p>
<input type="button" value="Add" onclick="addRowToTable();" />
<input type="button" value="Remove" onclick="removeRowFromTable();" />
</p>
If you are trying to dynamically add a row which has the Iteration Count as first data-cell (td), one input box as second cell and two input boxes placed one below the other as the third cell, you can try the following piece of code.
// right cell
var cellRight2 = row.insertCell(2);
var textNode = document.createTextNode('a');
cellRight2.appendChild(textNode);
var el1 = document.createElement('input');
el1.type = 'text';
el1.name = 'element_45_2' + iteration;
el1.id = 'element_45_2' + iteration;
el1.size = 40;
cellRight2.appendChild(el1);
var textNode = document.createTextNode('b');
cellRight2.appendChild(textNode);
var el2 = document.createElement('input');
el2.type = 'text';
el2.name = 'element_45_12' + iteration;
el2.id = 'element_45_12' + iteration;
el2.size = 40;
//el.onkeypress = keyPressTest;
cellRight2.appendChild(el2);
Based on your response, I think this is what you are looking for.
function addMoreVillageNames(){
rowNumber = (this.id).substring((this.id.length)-1, this.id.length); //to get Row Number where one more input needs to be added.
var parentCell = this.parentNode;
var inputCount = parentCell.getElementsByTagName('label').length; //to get the count of input fields present already
var newFieldNo = inputCount + 1; //input current count by 1 to dynamically set next number for the new field
parentCell.removeChild(this); //temporarily remove the add village button to insert the new field before it
var lineBreak = newElement('br');
parentCell.appendChild(lineBreak); //add a line break after the first field
var el_label = newElement('label');
el_label.for = 'village_text_' + rowNumber + '_' + newFieldNo;
var el_labelValue = newFieldNo + ' ';
var textNode = newTxt(el_labelValue);
el_label.appendChild(textNode);
parentCell.appendChild(el_label); //create and add label
var el_input = newElement('input');
el_input.type = 'text';
el_input.name = 'village_text_' + rowNumber + '_' + newFieldNo;
el_input.id = 'village_text_' + rowNumber + '_' + newFieldNo;
el_input.size = 40;
parentCell.appendChild(el_input); //create and add input field
var el_btn = newElement('input'); //add the village name add button again
el_btn.type = 'button';
el_btn.name = 'village_btn_' + rowNumber;
el_btn.id = 'village_btn_' + rowNumber;
el_btn.value = 'Add Village_' + rowNumber;
el_btn.addEventListener('click',addMoreVillageNames, false);
parentCell.appendChild(el_btn);
}
Use rowspan for making the a and b in same row.
<tr>
<td width="8" rowspan="2">1</td>
<td width="240" rowspan="2">
<input type="text" name="element_45_1"
id="element_45_1" size="40" />
</td>
<td width="20">
<div1>
a.
<input type="text" name="element_45_2"
id="element_45_2" size="40" />
</div1>
b.
<input type="text" name="element_45_12"
id="element_45_12" size="40" />
</td>
</tr>
Here is the working fiddle: Fiddle

Categories

Resources