Auto complete dynamically generated text box - javascript

I need help in filling the dynamically generated text boxes using jquery autocomplete.
Workflow:
1.On clicking add row button a row will be inserted.
2.On the inserted row,the product text box should be filled through auto complete.The same way all the dynamically generated text boxes should be filled by auto complete
Issue:
I have used the jquery auto complete function to fill the text boxes,but the auto complete function is working only for the text box in the first row.I need to fill all the dynamically created text boxes through auto complete function.
This is my code.
<html>
<head>
<script type="text/javascript" src="JS/jquery-1.4.2.min.js"></script>
<script src="JS/jquery.autocomplete.js"></script>
<script>
jQuery(function(){
$("#product").autocomplete("Productset.jsp");
});
</script>
<script type="text/javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowDelete = table.rows.length - 1;
if (rowDelete > 1)
table.deleteRow(rowDelete);
else
alert("Cannot delete all the rows.")
}
catch(e) {
alert(e);
}
}
</script>
</head>
<body>
<form>
<input type="button" value="Add Row" onclick="addRow('dataTable')" />
<input type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
<br/>
<br/>
<table id="dataTable" align="center" width="350px" border="1">
<tr>
<th> Product Name</th>
<th>Quantity</th>
<th> Brand</th>
</tr>
<tr>
<td> <input type="text" name="pname" id="product" value="" /></td>
<td><input type="text" name="qty" value=""/></td>
<td><select name="brand"/>
<select>
<option value="select">SELECT</option>
</select>
</td>
</table>
</form>
</body>
</html>
Productset.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="java.sql.*"%>
<%#page import="java.util.*"%>
<%
try{
String s[]=null;
Class.forName("com.mysql.jdbc.Driver");
Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/pdt","root","root");
Statement st=con.createStatement();
ResultSet rs = st.executeQuery("select distinct product from productlist");
List li = new ArrayList();
while(rs.next())
{
li.add(rs.getString(1));
}
String[] str = new String[li.size()];
Iterator it = li.iterator();
int i = 0;
while(it.hasNext())
{
String p = (String)it.next();
str[i] = p;
i++;
}
//jQuery related start
String query = (String)request.getParameter("q");
int cnt=1;
for(int j=0;j<str.length;j++)
{
if(str[j].toUpperCase().startsWith(query.toUpperCase()))
{
out.print(str[j]+"\n");
if(cnt>=5)// 5=How many results have to show while we are typing(auto suggestions)
break;
cnt++;
}
}
//jQuery related end
rs.close();
st.close();
con.close();
}
catch(Exception e){
e.printStackTrace();
}
%>

You need to call autocomplete in jquery 'on' function
$(document).on("focus","#product",function(e){
$(this).autocomplete("Productset.jsp");
});

When you add a new row you should call again the autocomplete function
$("#button").click(function(e) {
addRow();
$(".auto").autocomplete({
source: datas
});
});
https://jsfiddle.net/w78L1ho2/
if your Productset.jsp is not moving I recommand to call it only once.
To fill your datas with your text file you can do something like this
(convert text file to array comes from https://stackoverflow.com/a/6833016/5703316):
var datas = [];
function func(data) {
datas.push(data);
}
function readLines(input, func) {
var remaining = '';
input.on('data', function(data) {
remaining += data;
var index = remaining.indexOf('\n');
var last = 0;
while (index > -1) {
var line = remaining.substring(last, index);
last = index + 1;
func(line);
index = remaining.indexOf('\n', last);
}
remaining = remaining.substring(last);
});
input.on('end', function() {
if (remaining.length > 0) {
func(remaining);
}
});
}
$.get("Productset.jsp").done(function(result) {
readLines(result, func);
});

In my code the dynamically created text box doesn't take the jquery auto complete function.So including the auto complete function inside the addrow() method will fill the dynamically created text boxes with the auto complete data.
The id selector will only fill the first text box with the auto complete data.So use this $('input[name="product"]').auto complete("Productset.jsp"); in the jquery function to fill all the text boxes.
This is the complete code.
<html>
<head>
<script type="text/javascript" src="JS/jquery-1.4.2.min.js"></script>
<script src="JS/jquery.autocomplete.js"></script>
<script>
jQuery(function(){
$("#product").autocomplete("Productset.jsp");
});
</script>
<script type="text/javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
jQuery(function(){
$('input[name="product"]').autocomplete("Productset.jsp");
});
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
</script>
</head>
<body>
<form>
<input type="button" value="Add Row" onclick="addRow('dataTable')" />
<input type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
<br/>
<br/>
<table id="dataTable" align="center" width="350px" border="1">
<tr>
<th> Product Name</th>
<th>Quantity</th>
<th> Brand</th>
</tr>
<tr>
<td> <input type="text" name="product" id="product" value="" /></td>
<td><input type="text" name="qty" value=""/></td>
<td><select name="brand"/>
<select>
<option value="select">SELECT</option>
</select>
</td>
</table>
</form>
</body>
</html>

Related

How to count 1 option selected in dropdown from different rows added and display in textbox?

How to count 1 option selected in dropdown from different rows and display count in textbox?
I would like to count total value casualties of different rows and display count of total value casualties in textbox id injury.
Codes for dropdownlist && textbox && add row:
<select name="type" id="dd">
<option>Select a Type</option>
<option value="casualties">Casualties</option>
<option value="notcasualties">Not Casualties</option>
</select>
</select>
<label>Casualties:</label><input type="text" id="injury">
<btn><input type="button" value="addrow" onclick="addrow('dataTable2')" /></btn>
This codes are only able to display count = 1 in textbox id injury for the first row but not the added rows. I would like to total up count of value casualties after different rows are added. Could anyone help me.
$('#dd').change(function(){
var count = $('#dd option:selected').length;
$('.injury').val(count);
});
Thanks in advance!
Add onchange="select($(this).val())" in select tag and following function in script
function select(value){
if(value==="casualties"){
$("#injury").val(parseInt($("#injury").val())+1);
}
else{
$("#injury").val(parseInt($("#injury").val())-1);
if($("#injury").val()<0)
$("#injury").val("0");
}
}
and remove
$('#dd').change(function(){
var count = $('#dd option:selected').length;
$('.injury').val(count);
});
I made some changes that full fill your purpose
<html>
<head><title>table example</title></head>
<body>
<table id="dataTable2">
<tr>
<th></th>
<TH>Admin No/Staff ID:</TH>
<TH>Name:</TH>
<TH>Contact No:</TH>
<TH>Types of People Involved:</TH>
</TR>
<tr>
<td><input type="checkbox" name="checkbox[]"></td>
<TD><input type="text" name="id[]" id="id" /></TD>
<TD><input type="text" name="names[]" id="names"></TD>
<TD><input type="text" name="contacts[]" id="contacts" /> </TD>
<TD>
<select name="type" id="dd" class="selectpicker" data-style="select-with-transition" title="News Type" data-size="7" onchange="show()">
<option value="">Select a Type</option>
<option value="casualties" class="casualties-element">Casualties</option>
<option value="ncasualties">Non-Casualties</option>
<option value="witness">Witness</option>
</select>
</TD>
</tr>
</table>
<p>
<INPUT type="button" value="Add Row" onclick="addRow()" />
</p>
<table id="dataTable1" style="cellpadding:20px;">
<tr>
<th></th>
<TH>Admin No/Staff ID:</TH>
<TH>Name:</TH>
<TH>Contact No:</TH>
<TH>Types of People Involved:</TH>
</tr>
</table>
<p>
<label>No. of Casualties:</label>
<input type="text" name="injury" id="injury" class="injury span2" onClick="show();">
</p>
<script>
var count = 0;
function addRow() {
alert("test");
var table1 = document.getElementById('dataTable1');
var table = document.getElementById('dataTable2');
var did = document.getElementById('id').value;
var dname = document.getElementById('names').value;
var dcontact = document.getElementById('contacts').value;
var dddl = document.getElementById('dd');
var ddlvalue = dddl.options[dddl.selectedIndex].value;
if (ddlvalue == 'casualties') { count++; }
document.getElementById('injury').value = count;
var rowCount = table.rows.length;
//var row = table.insertRow(rowCount);
var row = table1.insertRow(1);
var colCount = table.rows[1].cells.length;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
//newcell.innerHTML = table.rows[1].cells[i].innerHTML;
//alert(newcell.childNodes);
switch (i) {
case 0:
newcell.innerHTML = did;
break;
case 1:
newcell.innerHTML = dname;
break;
case 2:
newcell.innerHTML = dcontact;
break;
case 3:
newcell.innerHTML = ddlvalue;
break;
}
}
}
</script>
</body>
</html>

Function in JavaScript doesn't work while the other function works

I have a form written in HTML. In this form there are 2 buttons, and a table. Each row in the table contains a checkbox, and 2 text fields.
The buttons are to add and remove rows from the table. The remove button apply only to rows where their checkbox is checked. They have an onClick method that refers to 2 methods written in JavaScript on a <script> tag below, addRow(tableID) and deleteRow(tableID).
The addRow(tableID) works when I click its buttons, but nothing happens when I click the remove button, which refers to deleteRow(tableID) method.
This is the code of the form:
<form action="Page2.php" method="post" enctype="multipart/form-data">
<!-- Contacts Details -->
<p>
<input type="button" value="Add Contact" onClick="addRow('contacts')" />
<input type="button" value="Remove Contact" onClick="deleteRow('contacts')" />
<p>(All actions apply only to entries with check marked check boxes only.)</p>
</p>
<table id="contacts" class="form" border="1">
<tbody>
<tr>
<p>
<td>
<input type="checkbox" name="chk[]" checked="checked" />
</td>
<td>
<label>Address</label>
<input type="text" name="ADDRESS[]" />
</td>
<td>
<label for="PHONE_NUMBER">Phone Number</label>
<input type="text" class="small" name="PHONE_NUMBER[]" />
</td>
</p>
</tr>
</tbody>
</table>
<script>
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if (rowCount < 10) {
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
}
} else {
alert("Maximum Contacts Number is 10");
}
}
function deleteRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
debugger;
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if (null != chkbox && true == chkbox.checked) {
if (rowCount <= 1) {
alert("Cannot Remove all Contacts");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
</script>
<!-- Form Sending -->
<input type="submit" value="Proceed">
</form>
EDIT #!:
I have just debugged the above code, and I found out that the variables chkbox and row from the deleteRow(tableID) method are shown in the debugger as undefined.
What can I do to fix this?
The problem is that using row.cells[0].childNodes[0] is an extremely brittle way to find nodes. You are retrieving a text node instead of the checkbox. Using
childNodes will break with even minimal changes to the HTML.
A more reliable way is to query for the element you are looking for
var chkbox = row.cells[0].querySelector('[type=checkbox]')
<form action="Page2.php" method="post" enctype="multipart/form-data">
<!-- Contacts Details -->
<p>
<input type="button" value="Add Contact" onClick="addRow('contacts')" />
<input type="button" value="Remove Contact" onClick="deleteRow('contacts')" />
<p>(All actions apply only to entries with check marked check boxes only.)</p>
</p>
<table id="contacts" class="form" border="1">
<tbody>
<tr>
<p>
<td>
<input type="checkbox" name="chk[]" checked="checked" />
</td>
<td>
<label>Address</label>
<input type="text" name="ADDRESS[]" />
</td>
<td>
<label for="PHONE_NUMBER">Phone Number</label>
<input type="text" class="small" name="PHONE_NUMBER[]" />
</td>
</p>
</tr>
</tbody>
</table>
<script>
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if (rowCount < 10) {
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
}
} else {
alert("Maximum Contacts Number is 10");
}
}
function deleteRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
debugger;
var row = table.rows[i];
var chkbox = row.cells[0].querySelector('[type=checkbox]');
if (null != chkbox && true == chkbox.checked) {
if (rowCount <= 1) {
alert("Cannot Remove all Contacts");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
</script>
<!-- Form Sending -->
<input type="submit" value="Proceed">
</form>

Deleting a table row from button click

The following code that I typed is used to add or delete rows in an html table. When I click the add button without any problem, but when I click the delete button though I want to delete a particular row I am unable to. I get an alert message stating:
"can not read property `onclick` of null "
How can I rectify this issue?
<HTML>
<HEAD>
<TITLE> Add/Remove dynamic rows in HTML table </TITLE>
<SCRIPT language="javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
//alert(newcell.childNodes);
switch (newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if (document.getElementById('button').onclick == true) {
if (rowCount <= 1) {
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
} catch (e) {
alert(e);
}
}
</SCRIPT>
</HEAD>
<BODY>
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
<TABLE id="dataTable" width="350px" border="1">
<TR>
<TD>
<INPUT type="button" name="button" value=delete id=delete onclick="deleteRow('dataTable')">
</TD>
</TR>
</TABLE>
</BODY>
</HTML>
The easiest way I've found to handle scenarios like these is to work with classes instead of ids, and also to use context. IDs are used as unique identifiers for items on your page. Because you will very likely have more than one 'remove button' on your page, it would be best to target them using a class name instead.
So what I would do if I were you is to include jQuery, it would make things a lot simpler for you.
Add the below line in your html document before the closing body tag.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
Add a 'removeRowBtn' class to your 'remove buttons'.
Then, for removing a row:
$(document).ready(function(){
$('body').on('click', '.removeRowBtn', function(){
// to make sure at least one row remains
if($('.removeRowBtn').length > 0){
$(this).parents('tr').remove();
}
});
});
And that's all you need. The above code uses context to target the parent row of the 'remove button' you are clicking on. No need to specify which table, calculate which row or how many rows are left etc.
First things first document.getElementById('button') returns undefined because you have no element in your page with id=button.
That is the error you are getting, but I think you should approach the deletion of your table rows slightly different.
The easiest way is this:
function deleteRow(elem) {
var table = elem.parentNode.parentNode.parentNode;
var rowCount = table.rows.length;
if(rowCount === 1) {
alert('Cannot delete the last row');
return;
}
// get the "<tr>" that is the parent of the clicked button
var row = elem.parentNode.parentNode;
row.parentNode.removeChild(row); // remove the row
}
and use this function as the click event handler on each button:
<table>
<tr>
<td><button onclick="deleteRow(this)">delete</button></td>
</tr>
</table>
There's no need to create deleteRow(tableID) because by doing this you are trying to override the default deleteRow function of javascript so instead of creating a deleteRow(tableID) just add 'document.getElementById('dataTable').deleteRow(this.rowIndex)' to onclick of the delete button
<input type="button" name="button" value=delete id=delete onclick="document.getElementById('dataTable').deleteRow(this.rowIndex)">
You can use below method to delete a particular row.
SCRIPT METHOD:
function deleteRow(element,tableID) {
try {
var tableElement = document.getElementById(tableID);
if(tableElement.rows.length <= 1){
alert("Cannot delete all the rows.");
return;
}
var x = element.parentElement;//td tag
x = x.parentElement;// tr tag
x.remove();
}catch(e) {
alert(e);
}
}
BUTTON ELEMENT IN TD
<TD><INPUT type="button" name="button" value=delete id=delete onclick="deleteRow(this,'dataTable')"></TD>
<div class="table-responsive">
<table class="table" id="testTable">
<thead>
<tr>
<th>Col1</th>
<th>Col2</th>
<th>Type</th>
<th>Remove</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" id="mainScript" name="mainScript"></td>
<td><input type="text" id="rollBackScript" name="rollBackScript"></td>
<td><select name="type" id ="type" >
<option value="Automated" selected >Automated</option>
<option value="Manual" >Manual</option>
</select>
</td>
<td><input type="button" class="btn btn-danger" value="Delete" onclick="deleteRow(this);"></td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="row" align="left">
<input type="button" class="btn btn-success" value="Add Row" onclick="addRow('scriptsTable')" />
</div>
JavaScript functions
<script>
function addRow(tableId) {
var table = document.getElementById(tableId);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[1].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
case "button":
newcell.childNodes[0].value = "Delete";
break;
}
}
}
function deleteRow(deleteBtn) {
var table = document.getElementById('scriptsTable');
if(table.rows.length <= 2){
alert("Cannot delete all the rows.");
return;
}
if (typeof(deleteBtn) == "object") {
$(deleteBtn).closest("tr").remove();
} else {
return false;
}
}
</script>
Try this one. this is working example
<table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Position</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Tiger Nixon</td>
<td>System Architect</td>
<td><button>Delete</button></td>
</tr>
</tbody>
</table>
<script>
$(document).ready(function () {
var table = $('#example').DataTable({
"columns": [
null,
null,
null,
{
"sortable": false
}
]
});
});
$('#example').on("click", "button", function(){
console.log($(this).parent());
table.row($(this).parents('tr')).remove().draw(false);
});
</script>

How to hide and show table that is populated via a form

Below is a form when submitted displays the content in a table.
What works
Content is successfully transferred via form to table.
What is not working
I wanted to hide the table when the page loads and be displayed only after the form is submitted.
I tried #myTableData {visibility: hidden;} in css and then I tried plugging (.style.visibility="visible";) Javascript in my addtable function to display the table but it does not work. I am not sure if I am understanding this right.
Also how do I control the display of the table (like width, background color, font etc). I added (td.style.width = '200px'; but I don't see any changes).
CSS or JS for controlling table ?
function addTable() {
var table = document.createElement('TABLE').style.display = "block";
table.border='0';
for (var i=0; i<3; i++){
var tr = document.createElement('tr');
for (var j=0; j<4; j++){
var td = document.createElement('td');
td.style.width = '200px';
td.appendChild(document.createTextNode("Cell " + i + "," + j));
tr.appendChild(td);
}
}
}
function addRow() {
var myName = document.getElementById("name");
var domainName = document.getElementById("domain");
var url = document.getElementById("url");
var table = document.getElementById("myTableData");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
//row.insertCell(0).innerHTML= '<input type="button" value = "Delete" onClick="Javacsript:deleteRow(this)">';
row.insertCell(0).innerHTML= myName.value;
row.insertCell(1).innerHTML= domainName.value;
row.insertCell(2).innerHTML= url.value;
}
function load() {
console.log("Check if this loads");
}
/*
function deleteRow(obj) {
var index = obj.parentNode.parentNode.rowIndex;
var table = document.getElementById("myTableData");
table.deleteRow(index);
}
*/
#myTableData {visibility: hidden;}
body {
background: gray;
}
<!DOCTYPE html>
<html>
<head>
<title>HTML dynamic table using JavaScript</title>
<script type="text/javascript" src="table-app.js"></script>
<link rel="stylesheet" href="table-app.css">
</head>
<body onload="load()">
<div id="myform">
<b>Simple form with name and age ...</b>
<table>
<tr>
<td>Name</td>
<td><input type="text" id="name"></td>
</tr>
<tr>
<td>Domain</td>
<td><input type="text" id="domain">
</td>
</tr>
<tr>
<td>URL</td>
<td><input type="text" id="url"></td>
</tr>
<tr>
<td colspan=2><input type="button" id="add" value="Display as Table" onclick="Javascript:addRow()"></td>
</tr>
</table>
</div>
<table id="myTableData" border="1" cellpadding="2">
<tr>
<th>Name</td>
<th>Domain</th>
<th>URL</th>
</tr>
</table>
</div>
<!--
<div id="myDynamicTable">
<input type="button" id="create" value="Click here" onclick="Javascript:addTable()">
to create a Table and add some data using JavaScript
</div> -->
</body>
</html>
1) In function addRow add table.style.visibility = "visible"; ,to display the table, right after var table = document.getElementById("myTableData");.
2) To set styles like width you can can use setAttribute method.
document.getElementById('myTableData').setAttribute("style","width:200px");
Note: I can't see where you make use of addTable function, maybe this is why some of styles are not setted when you want.
function addTable() {
var table = document.createElement('TABLE').style.display = "block";
table.border='0';
for (var i=0; i<3; i++){
var tr = document.createElement('tr');
for (var j=0; j<4; j++){
var td = document.createElement('td');
td.style.width = '200px';
td.appendChild(document.createTextNode("Cell " + i + "," + j));
tr.appendChild(td);
}
}
}
function addRow() {
var myName = document.getElementById("name");
var domainName = document.getElementById("domain");
var url = document.getElementById("url");
var table = document.getElementById("myTableData");
table.style.visibility = "visible";
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
//row.insertCell(0).innerHTML= '<input type="button" value = "Delete" onClick="Javacsript:deleteRow(this)">';
row.insertCell(0).innerHTML= myName.value;
row.insertCell(1).innerHTML= domainName.value;
row.insertCell(2).innerHTML= url.value;
}
function load() {
console.log("Check if this loads");
}
/*
function deleteRow(obj) {
var index = obj.parentNode.parentNode.rowIndex;
var table = document.getElementById("myTableData");
table.deleteRow(index);
}
*/
#myTableData {visibility: hidden;}
body {
background: gray;
}
<!DOCTYPE html>
<html>
<head>
<title>HTML dynamic table using JavaScript</title>
<script type="text/javascript" src="table-app.js"></script>
<link rel="stylesheet" href="table-app.css">
</head>
<body onload="load()">
<div id="myform">
<b>Simple form with name and age ...</b>
<table>
<tr>
<td>Name</td>
<td><input type="text" id="name"></td>
</tr>
<tr>
<td>Domain</td>
<td><input type="text" id="domain">
</td>
</tr>
<tr>
<td>URL</td>
<td><input type="text" id="url"></td>
</tr>
<tr>
<td colspan=2><input type="button" id="add" value="Display as Table" onclick="Javascript:addRow()"></td>
</tr>
</table>
</div>
<table id="myTableData" border="1" cellpadding="2">
<tr>
<th>Name</td>
<th>Domain</th>
<th>URL</th>
</tr>
</table>
</div>
<!--
<div id="myDynamicTable">
<input type="button" id="create" value="Click here" onclick="Javascript:addTable()">
to create a Table and add some data using JavaScript
</div> -->
</body>
</html>
I don't have the rep to comment so I can't ask for details, but just in case you can use jquery, you can hide and show stuff like this:
$(function(){
$("#add").click(function() {
var name = $('#name').val();
var domain = $('#domain').val();
var url = $('#url').val();
$('#hidey').show();
$('#nametd').html(name);
$('#domtd').html(domain);
$('#urltd').html(url);
})
});
https://jsfiddle.net/6dxLsnL4/
Or trigger on form submit instead of click if you want, but there, you might want to consider ajax, because then you can make sure the form is processed on the server side before displaying the results.

javascript dynamically add delete row nested

I've run into a problem with adding and deleting blank rows in javascript... it's a nesting issue and unique id issue.
To summarize, I have three form fields. Field1, Amount1, Amount2. Field1 can have multiple Amount1 & Amount2. There can be multiple Field1 as well, which also can have mutiple Amount1, Amount2. The problem is that my "Add" buttons copies the extra Amount1, Amount2 (when exists). Just to explain, the "Add row" adds Amount1,Amount2. The "Delete Row" deletes Amount1,Amount2 when the checkbox is checked.
When I click the "Add" button, I want a new Field1, Amount1, Amount2 but no additional Amount1,Amount2. And when I click "Add Row" or "Delete Row" in the additional sets of form fields, I want it to add or delete the Amount1,Amount2 in that particular set.
I need to assign a unique identifier to each entire row to get this to work but cannot figure it out.
Here is my code, which will probably make more sense if it's executed.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd"><head>
<script type="text/javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.row[0].cells [i].innerHTML; //alert (newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
if(rowCount <= 1) {
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e)
{
alert(e);
}
}
var _counter = 0;
function Add() {
_counter++;
var oClone = document.getElementById("template").cloneNode(true);
oClone.id += (_counter + "");
document.getElementById("placeholder").appendChild(oClone);
}
</script>
</head>
<body>
<fieldset id="fieldset">
<div id="placeholder">
<div id="template">
<br>
<table id= "act_legis">
<tr>
<td>Field1:</td>
<td>Amount1:</td>
<td>Amount2:</td>
<td> </td>
</tr>
</table>
<table id= "act">
<tr>
<td>
<button type="button" name="Submit"
align = "left" onclick="Add();">Add</button>
<input name="Field1" type="text" size="4" maxlength="4"/></td>
</tr>
</table>
<table id= "legis_amounts">
<tr>
<td>
<input type="checkbox" name="chk"/>
<input name="Amount1" type="text" size="10"maxlength="18"/>
</td>
<td>
<input name="Amount2" type="text" size="10" maxlength="18"/>
</td>
</tr>
</table>
<table>
<tr>
<td>
<input type="button" onclick="addRow('legis_amounts');
return false;" value = "add row"/>
<input type="button" value = "delete row" onclick="deleteRow
('legis_amounts');return false;" />
</td>
</tr>
</table>
</div> <!-- template -->
</div> <!-- placeholder -->
</fieldset>
<table>
<tr>
<td><p> </p>
</td>
</tr>
</table>
</body>
</html>

Categories