javascript dynamic input fields - javascript

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

Related

delete button to remove entire row of Firebase data

I am having trouble with what seems like it should be simple. I want to remove an entire row in an HTML table that is holding data from Firebase. I have been able to remove the entire Firebase parent node of users on click of "Delete" from the delete_row function, but I would like to only remove the row that the delete button was clicked on. Thanks in advance!
// table
<table style="width:100%">
<tr>
<td>Id: </td>
<td><input type="text" name="id" id="user_id" /></td>
</tr>
<tr>
<td>Place Name: </td>
<td><input type="text" name="user_name" id="user_name" /></td>
</tr>
<tr>
<td colspan="2">
<input type="button" value="Add Place" onclick="create_row();" />
<input type="button" value="Delete" onclick="delete_row();" />
</td>
</tr>
</table>
<table id="tbl_users_list" border="1">
<tr>
<td>#Id</td>
<td>PLACE NAME</td>
</tr>
</table>
// script to create and delete rows
<script>
var tblUsers = document.getElementById("tbl_users_list");
// firebase reference
var database = firebase.database().ref('users/');
var rowIndex = 1;
database.once('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var childKey = childSnapshot.key;
var childData = childSnapshot.val();
var row = tblUsers.insertRow(rowIndex);
var cellId = row.insertCell(0);
var cellName = row.insertCell(1);
var cellButtons = row.insertCell(2).outerHTML="<tr id='row"+rowIndex+"'><td><input type='button' value='Delete' class='delete' onclick='delete_row()'></td></tr>";
cellId.appendChild(document.createTextNode(childKey));
cellName.appendChild(document.createTextNode(childData.user_name));
rowIndex = rowIndex + 1;
});
});
function create_row() {
var user_name = document.getElementById('user_name').value;
var uid = firebase.database().ref().child('users').push().key;
var data = {
user_id: uid,
user_name: user_name
}
var updates = {};
updates['/users/' + uid] = data;
firebase.database().ref().update(updates);
alert('the user was created successfully');
reload_page();
}
function delete_row() {
var key = document.getElementById(row).row.childData;
firebase.database().ref().child('users/' + row + '/').remove();
alert('row was removed');
reload_page();
}
function reload_page() {
window.location.reload();
}
</script>
You can pass the childKey to your delete_row() method. This way you can tell Firebase which node to delete:
database.once('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var childKey = childSnapshot.key;
var childData = childSnapshot.val();
var row = tblUsers.insertRow(rowIndex);
var cellId = row.insertCell(0);
var cellName = row.insertCell(1);
var cellButtons = row.insertCell(2).outerHTML=
"<tr id='row"+rowIndex+"'><td><input type='button' value='Delete' class='delete' onclick='delete_row("+childKey+")'></td></tr>";
cellId.appendChild(document.createTextNode(childKey));
cellName.appendChild(document.createTextNode(childData.user_name));
rowIndex = rowIndex + 1;
});
});
function delete_row(childKey) {
var key = document.getElementById(row).row.childData;
firebase.database().ref().child('users/' + childKey + '/').remove();
alert('row was removed');
reload_page();
}
So I am facing a similar kind of issue. The main problem is that for all the delete buttons the same key is being passed.
userImagesRef1.once("value", function(snapshot) {
var ParentKey = snapshot.key;
console.log(ParentKey);
snapshot.forEach(function(childSnapshot) {
childSnapshot.forEach(function(snap){
childKey = snap.key;
console.log(childKey);
// alert("child key" + childKey);
var TenderID = snap.child("TenderID").val();
console.log(TenderID);
var NoticeNumber = snap.child("NoticeNumber").val();
var NameofWork = snap.child("NameofWork").val();
var pictures = snap.child("pictures").val();
Link1 = pictures[0];
console.log(Link1);
Link2 = pictures[1];
console.log(pictures[1]);
var Link3 = pictures[2];
console.log(Link3)
if(Link3 == undefined){
Link3 = " ";
}
if(Link3 == null){
Link3 = " ";
}
var Service = String(snap.child("Service").val());
console.log(Service)
var ts = snap.child("timestamp").val();
console.log("TS:" + ts);
var SNo = "";
var id = snap.child("id").val();
var Corrigendum = snap.child("Corrigendum").val();
var State = snap.child("Status").val();
var StartDate = snap.child("StartDate").val();
var EndDate = snap.child("EndDate").val();
var Remarks = snap.child("Remarks").val();
$("#tableBody").append("<tr><td>"+ SNo +"</td><td>"+ id +"</td><td><p>"+TenderID+"</p><p><a href = '" + Link1+"'>" +NoticeNumber+"</p></td>"+"<td>" +NameofWork+"</td><td>" + StartDate + "</td><td>"+EndDate+"</td><td>" + Corrigendum + "</td> <td><a href = '" +Link2+ "'>" +Remarks+"</a></td><td>"+ State +"'<input type='button' value='Delete' class='delete' onclick='delete_row(childKey)'>"+"</td></tr>" );
})
});
});
function delete_row(childKey) {
// var key = document.getElementById(row).row.childData;
// alert("12232");
alert(childKey);
firebase.database().ref().child('user-images/' + childKey + '/').remove();
alert('row was removed');
// reload_page();
}

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>

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];

accessing values of dynamic table row using 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.

JavaScript to show extra form fields

I have a form that has a block called "Product", containing text inputs. Inside that block, the user can press "add item" and have the JS show one more field. Till now everything works.
I've tried to add a function for adding a new "Product" block but no luck. Do you have any hints for me?
Product
Item: <input> Price: <input>
Item: <input> Price: <input>
<a>add item</a> <- this works
<a>add Product</a> <- this is the part that I can't figure out :(
Any help will be appreciated.
Thank you!
Update:
Here is the JS for the Item and Price fields:
<script type="text/javascript">
$(document).ready(function(){
var counter = 2;
$("b.add-item").click(function () {
if(counter>5){ alert("Max 6 items allowed"); return false; }
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html(
'<span class="item">' +
'<label>Item:</label>'+
'<input type="text" name="item1[]" id="textbox' + counter + '" value="" >' +
'<label> Price:</label>'+
'<input type="text" name="price1[]" id="textbox' + counter + '" value="" >' +
'</span>'
);
newTextBoxDiv.appendTo(".items");
counter++;
});
$("b.remove-item").click(function () {
if(counter==1){alert("No more textbox to remove");
return false; } counter--;
$("#TextBoxDiv" + counter).remove();});
$("#getButtonValue").click(function () { var msg = ''; for(i=1; i<counter; i++){ msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val(); }alert(msg); });
});
</script>
Maybe make a table and add new rows?
HTML:
<table id="myTable">
<tr>
<th>Item</th>
<td><input /></td>
<th>Price</th>
<td><input /></td>
</tr>
<tr>
<th>Item</th>
<td><input /></td>
<th>Price</th>
<td><input /></td>
</tr>
</table>
<a onclick="add_row(); return false;">Add Product</a>
JavaScript:
function add_row()
{
var table = document.getElementById('myTable');
if(!table) return;
// Table row
var row = document.createElement('row');
table.appendChild(row);
// "Item:"
var th1 = document.createElement('th');
th1.innerText = 'Item:'
row.appendChild(th1);
// Item input
var td1 = document.createElement('td');
row.appendChild(td1);
var input1 = document.createElement('input');
td1.appendChild(input1);
// "Price:"
var th2 = document.createElement('th');
th2.innerText = 'Price:'
row.appendChild(th2);
// Price input
var td2 = document.createElement('td');
row.appendChild(td2);
var input2 = document.createElement('input');
td1.appendChild(input2);
}
I think this should work...

Categories

Resources