add image input with jquery with limit to four - javascript

I have this code that a user can upload pictures. It works just fine, but the user can submit unlimited pictures, and I want to put a limit to four.
when the user reaches four input fields then they won't be allowed to add any input.
<script type="text/javascript">
function addItems()
{
var table1 = document.getElementById('tab1');
var newrow = document.createElement("tr");
var newcol = document.createElement("td");
var input = document.createElement("input");
input.type="file";
input.name="image[]";
newcol.appendChild(input);
newrow.appendChild(newcol);
table1.appendChild(newrow);
}
function remItems()
{
var table1 = document.getElementById('tab1');
var lastRow = table1.rows.length;
if(lastRow>=2)
table1.deleteRow(lastRow-1);
}
</script>
<form method="post" action="" enctype="multipart/form-data">
<table align="center" border="0" id="tab1">
<tr>
<td width="218" align="center">
<input type="file" name="image[]" /></td>
<td width="54" align="center">
<img src="Button-Add-icon.png" alt="Add" style="cursor:pointer"
onclick="addItems()" /></td>
<td>
<img src="Button-Delete-icon.png" alt="Remove" style="cursor:pointer"
onclick="remItems()" /></td>
</tr>
</table>
<table align="center" border="0" id="tab2">
<tr><td align="center">
<input type="submit" value="Upload" name="upload" /></td></tr>
</table>
</form>
Thanks

Add a global counter.. and check on your addItems function.. something like:
var totalItems = 0;
function addItems()
{
if(totalItems < 4) {
var table1 = document.getElementById('tab1');
var newrow = document.createElement("tr");
var newcol = document.createElement("td");
var input = document.createElement("input");
input.type="file";
input.name="image[]";
newcol.appendChild(input);
newrow.appendChild(newcol);
table1.appendChild(newrow);
totalItems++; //increment the global counter...
} else {
//Display your message here.. with an alert or something...
}
}
function remItems()
{
var table1 = document.getElementById('tab1');
var lastRow = table1.rows.length;
if(lastRow>=2) {
table1.deleteRow(lastRow-1);
totalItems--;
}
}

Related

Adding buttons to each row of a table to remove said row

just looking for a simple solution on solving this, Consider the the following code:
<!DOCTYPE html>
<html>
<head>
<title>Javascript - Add HTML Table Row </title>
<meta charset="windows-1252">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<form>
<script>
function addRow()
{
// get input values
var name = document.getElementById('name').value;
var currentAge =
document.getElementById('currentAge').value;
var Birthday = document.getElementById('Birthday').value;
var carType = document.getElementById('carType').value;
var Delete = document.getElementById('Delete').value;
var table = document.getElementsByTagName('table')[0];
var newRow = table.insertRow(table.rows.length/2+1);
var cel1 = newRow.insertCell(0);
var cel2 = newRow.insertCell(1);
var cel3 = newRow.insertCell(2);
var cel4 = newRow.insertCell(3);
var cel5 = newRow.insertCell(4);
cel1.innerHTML = name;
cel2.innerHTML = currentAge;
cel3.innerHTML = Birthday;
cel4.innerHTML = carType;
cel5.innerHTML = Delete;
function myFunction(){
var x = document.getElementById("table").rows.length;
document.getElementById("demo").innerHTML = "Found " + x + " tr
elements in the table.";
}
</script>
</form>
</head>
<style>
table, th {
border: 1px solid black;
}
tbody td{
padding: 30px;
}
tbody tr:nth-child(odd){
background-color: #F4BC01;
color: #ABC412;
}
$("")
</style>
<body>
<h2>Basic HTML table</h2> <button onclick="myFunction()">Press me for
elements amount</button>
<p id ="demo"></p>
Name: <input type="text" name="name" id="name" /><br/><br/>
Age: <input type="text" name="currentAge" id="currentAge" /><br/><br/>
Date of Birth <input type="date" name="Birthday" id="Birthday" /><br/>
<button onclick="addRow();">Display</button><br/><br/>
<p>Eye Colour:</p>
<select id="carType">
<option value="ferrari" id="ferrari">Ferrari</option>
<option value="lamborghini" id="lamborghini">Lamborghini</option>
<option value="porsche" id="porsche">Porsche</option>
<option value="bugatti" id="bugatti">Bugatti</option>
<option value="pagani" id="pagani">Pagani</option>
</select>
<table border="1" id="table">
<tr>
<th>Name</th>
<th>Age</th>
<th>Birthday</th>
<th>CarType</th>
<th>Delete Entry
<button id="Delete" onclick="remove_update(event)">delete</button> //this button right here but in each row and not here. should remove said row
</th>
</tr>
</table>
</body>
</html>
What im trying to do is within cel 5 (delete entry) is to add a delete button to each row that is entered into the table that will remove that row but don't know how to go about this. Ideally would like to do this without the use of JQuery if possible, since i've not touched upon it as of yet.
You can use the rowIndex property to delete the row.
function addRow() {
// get input values
var name = document.getElementById('name').value;
var currentAge = document.getElementById('currentAge').value;
var Birthday = document.getElementById('Birthday').value;
var carType = document.getElementById('carType').value;
var table = document.getElementsByTagName('table')[0];
const index = table.rows.length;
var newRow = table.insertRow(index);
newRow.setAttribute('data-index', index);
var cel1 = newRow.insertCell(0);
var cel2 = newRow.insertCell(1);
var cel3 = newRow.insertCell(2);
var cel4 = newRow.insertCell(3);
var cel5 = newRow.insertCell(4);
cel1.textContent = name;
cel2.textContent = currentAge;
cel3.textContent = Birthday;
cel4.textContent = carType;
cel5.innerHTML = '<button onclick="removeRow(this)" type="button" class="delete-button">Delete</button>';
}
function myFunction() {
var x = document.getElementById("table").rows.length;
document.getElementById("demo").innerHTML = "Found " + x + "tr elements in the table.";
}
function removeRow(evt) {
const deleteIndex = evt.parentElement.parentElement.rowIndex;
document.getElementById("table").deleteRow(deleteIndex);
}
table,
th {
border: 1px solid black;
}
tbody td {
padding: 30px;
}
tbody tr:nth-child(odd) {
background-color: #F4BC01;
color: #ABC412;
}
<h2>Basic HTML table</h2> <button onclick="myFunction()">Press me for
elements amount</button>
<p id ="demo"></p>
Name: <input type="text" name="name" id="name" /><br/><br/>
Age: <input type="text" name="currentAge" id="currentAge" /><br/><br/>
Date of Birth <input type="date" name="Birthday" id="Birthday" /><br/>
<button onclick="addRow();">Display</button><br/><br/>
<p>Eye Colour:</p>
<select id="carType">
<option value="ferrari" id="ferrari">Ferrari</option>
<option value="lamborghini" id="lamborghini">Lamborghini</option>
<option value="porsche" id="porsche">Porsche</option>
<option value="bugatti" id="bugatti">Bugatti</option>
<option value="pagani" id="pagani">Pagani</option>
</select>
<table border="1" id="table">
<tr>
<th>Name</th>
<th>Age</th>
<th>Birthday</th>
<th>CarType</th>
<th>Delete</th>
</tr>
</table>
</body>
</html>
What you should be doing is that you set the innerHTML of cel5 to a button, e.g.:
cel5.innerHTML = '<button type="button" class="delete-button">Delete</button>';
Then, you can simply add a click event listener on the table, and check if a click event has emitted from the button element. If it matches, you then delete the closest <tr> element:
document.getElementById('table').addEventListener('click', function(e) {
// Check if click event came from delete button
if (!e.target.classList.contains('delete-button'))
return;
e.target.closest('tr').remove();
});
See proof-of-concept example below:
function addRow() {
// get input values
var name = document.getElementById('name').value;
var currentAge = document.getElementById('currentAge').value;
var Birthday = document.getElementById('Birthday').value;
var carType = document.getElementById('carType').value;
var table = document.getElementsByTagName('table')[0];
var newRow = table.insertRow(table.rows.length / 2 + 1);
var cel1 = newRow.insertCell(0);
var cel2 = newRow.insertCell(1);
var cel3 = newRow.insertCell(2);
var cel4 = newRow.insertCell(3);
var cel5 = newRow.insertCell(4);
cel1.innerHTML = name;
cel2.innerHTML = currentAge;
cel3.innerHTML = Birthday;
cel4.innerHTML = carType;
cel5.innerHTML = '<button type="button" class="delete-button">Delete</button>';
}
function myFunction() {
var x = document.getElementById("table").rows.length;
document.getElementById("demo").innerHTML = "Found " + x + "tr elements in the table.";
}
document.getElementById('table').addEventListener('click', function(e) {
// Check if click event came from delete button
if (!e.target.classList.contains('delete-button'))
return;
e.target.closest('tr').remove();
});
<h2>Basic HTML table</h2> <button onclick="myFunction()">Press me for
elements amount</button>
<p id="demo"></p>
Name: <input type="text" name="name" id="name" /><br/><br/> Age: <input type="text" name="currentAge" id="currentAge" /><br/><br/> Date of Birth <input type="date" name="Birthday" id="Birthday" /><br/>
<button onclick="addRow();">Display</button><br/><br/>
<p>Eye Colour:</p>
<select id="carType">
<option value="ferrari" id="ferrari">Ferrari</option>
<option value="lamborghini" id="lamborghini">Lamborghini</option>
<option value="porsche" id="porsche">Porsche</option>
<option value="bugatti" id="bugatti">Bugatti</option>
<option value="pagani" id="pagani">Pagani</option>
</select>
<table border="1" id="table">
<tr>
<th>Name</th>
<th>Age</th>
<th>Birthday</th>
<th>CarType</th>
<th>Actions</th>
</tr>
</table>
In the head, add a function that understands rows and cells. Call some delete on a parent of a cell (Delete the <tr> in which the <td> is located at). then on the body add to each dynamic button an onClick event and set that function you created earlier ON.
You can use a script like this:
function deleteRow() {
var tableData = event.target.parentNode;
var tableRow = tableData.parentNode;
tableRow.parentNode.removeChild(tableRow);
}
In the button you create (dynamically or fixedly) you should add an onClick event. For example:
<tr>
<td>John Doe</td>
<td>$10,000</td>
<td><input type="submit" value="Delete" id="Delete" onclick="deleteRow()"></td>
</tr>

how to insert generated html table data into database in php?

How I can insert all data from a generated HTML table into my database using PHP?
I have tried with a foreach loop, but it gives me an error all the time.
I have this code in JavaScript to adding a new row using a button:
var i=1;
function addRow()
{
var tbl = document.getElementById('table1');
var lastRow = tbl.rows.length;
var iteration = lastRow - 1;
var row = tbl.insertRow(lastRow);
var firstCell = row.insertCell(0);
var el = document.createElement('input');
el.type = 'text';
el.name = 'to' + i;
el.id = 'to' + i;
el.size = 40;
firstCell.appendChild(el);
var secondCell = row.insertCell(1);
var el2 = document.createElement('input');
el2.type = 'text';
el2.name = 'cost' + i;
el2.id = 'cost' + i;
el2.size = 40;
secondCell.appendChild(el2);
frm.h.value=i;
i++;
}
And this is my HTML code:
<table id="table1" width="40%" border="2" cellpadding="0" cellspacing="0">
<tr>
<td><strong>To Address</strong></td>
<td><strong>Delivery Cost</strong></td>
</tr>
<tr>
<td><input name="to" type="text" id="to" size="40"/></td>
<td><input name="cost" type="text" id="cost" size="40"/></td>
</tr>
</table>
<br/><br/>
<input style="float: right;background-color: #57a000;height: 30px;font-weight: bold; font-family: cursive;margin-left: 10px;"
type="submit" value="Save All" name="SaveCost"/>
<input style="float: right;background-color: #57a000;height: 30px;font-weight: bold; font-family: cursive;"
type="button" value="Add New Place" onclick="addRow();"/>
<input name="h" type="hidden" id="h" value="0"/>
Finally I want to write some PHP to insert all the data from the generated HTML table into my database.

I have a table in jsp which have 5 rows and 3 colums and i wanted to print it in servlet how can i do this?

<script>
function addRow() {
var medicinename = document.getElementById("medicinename");
var time = document.getElementById("time");
var duration = document.getElementById("duration");
var when = document.getElementById("when");
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(1).innerHTML= medicinename.value;
row.insertCell(2).innerHTML= time.value;
row.insertCell(3).innerHTML= duration.value;
row.insertCell(4).innerHTML= when.value;
document.getElementById('medicinename').value='';
document.getElementById('time').value='';
document.getElementById('duration').value='';
document.getElementById('when').value='';
}
function deleteRow(obj) {
var index = obj.parentNode.parentNode.rowIndex;
var table = document.getElementById("myTableData");
table.deleteRow(index);
}
function addTable() {
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border='1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i=0; i<3; i++){
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j=0; j<4; j++){
var td = document.createElement('TD');
td.width='75';
td.appendChild(document.createTextNode("Cell " + i + "," + j));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
</script>
<table>
<tr>
<td>Medicine Name:</td>
<td><input type="text" id="medicinename"></td>
</tr>
<tr>
<td>Time:</td>
<td><input type="text" id="time">
</tr>
<tr>
<td>Duration:</td>
<td><input type="text" id="duration">
</tr>
<tr>
<td>When?</td>
<td><input type="text" id="when">
<input type="button" id="add" value="Add" onclick="Javascript:addRow()"></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
<div id="mydata">
<table id="myTableData" border="1" cellpadding="2">
<tr>
<td> </td>
<td><b>Medicine Name</b></td>
<td><b>Medicine Time&nbsp</b></td>
<td><b>Medicine Duration</b></td>
<td><b>Medicine When?</b></td>
</tr>
</table>
here is JAVASCRIPT through which i add element in JSP table
here is my 4 field and table which display data inside JSP
hello = request.getParameter("");//what should i take here
System.out.println(hello);
You need to collect your table data in JavaScript by the use a form or Ajax to send this data to your servlet. You can't get the table data from request parameters in servlet unless you send it.
An example of form
<form action="login" method="post">
<input type="text" name="uname" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<button type="submit" class="button" >Login</button>
</form>
This form pass uname and password to login Servlet.
You can pass each data in table like this way...!
In servlet side you can use this code for fetch data
String uname = request.getParameter("uname");
String password = request.getParameter("password");
just try out..!
Since, you were using jQuery and Servlet but you edited your question and removed the code. But here is some code example using jQuery.
Sample Table :
<table id='table_id'>
<th>Column1</th><th>Column2</th>
<tr>
<td>1</td><td>2</td>
</tr>
<tr>
<td>3</td><td>4</td>
</tr>
</table>
First you need to iterate through your table in javascript, create a JSON object with table data. Probably like this (see the table structure given here)
<script type="text/javascript" >
function collectData(){
var tableData = [];
$('#table_id tr').each(function(){
var $this = $(this);
var tds = $this.find('td');
var i = 0;
//if we have data in that row
if(tds.length){
var rowData = {
column1:tds[0].innerHTML,
column2:tds[1].innerHTML,
}
tableData.push(rowData);
}
});
console.log(tableData);
// Send it via AJAX
$.ajax({
url: '/yourServletName', // Change name to your servlet
type: 'POST',
dataType: 'json',
data: {objarray: JSON.stringify(tableData)},
success: function(result) {
alert('SUCCESS');
}
});
}
JSON will be like :
{
[{'column1':1,'column2':2}, {'column1':3,'column2':4}]
}
Now in your servlet code access this data using
String tableArray = request.getParameter("objarray").
But you need to convert the JSON to Java Pojo Object. Create a class similar to your table and parse the JSON using any library like jackson or gson
public class TableData{
private String column1;
private String column2;
public String getColumn1(){
return column1;
}
public void setColumn1(String column1){
this.column1 = column1;
}
public String getColumn2(){
return column2;
}
public void setColumn2(String column2){
this.column2 = column2;
}
}
GSON tutorial is given here
As explained in another answer, either use input elements in form or use JSON object as given in another answer here.
Form input method
HTML or JSP
<table>
<tr>
<td>Medicine Name:</td>
<td><input type="text" id="medicinename"></td>
</tr>
<tr>
<td>Time:</td>
<td><input type="text" id="time">
</tr>
<tr>
<td>Duration:</td>
<td><input type="text" id="duration">
</tr>
<tr>
<td>When?</td>
<td><input type="text" id="when">
<input type="button" id="add" value="Add" onclick="Javascript:addRow()"></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
<div id="mydata">
<form action="yourServletName" method="post">
<table id="myTableData" border="1" cellpadding="2">
<tr>
<td> </td>
<td><b>Medicine Name</b></td>
<td><b>Medicine Time&nbsp</b></td>
<td><b>Medicine Duration</b></td>
<td><b>Medicine When?</b></td>
</tr>
</table>
<button type="submit" class="button" >Submit</button>
<!-- Update the rowCount on Submitting the button -->
<input type="hidden" id="rowCount" value="" />
</form>
</div>
JS File to add input in table, you can :
function addRow() {
var medicinename = document.getElementById("medicinename");
var time = document.getElementById("time");
var duration = document.getElementById("duration");
var when = document.getElementById("when");
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(1).innerHTML= '<input type="text" name="'+'rowMedicine'+rowCount+'" value="'+medicinename.value+'" readonly />';
row.insertCell(2).innerHTML= '<input type="text" name="'+'rowTime'+rowCount+'" value="'+time.value+'" readonly />';
row.insertCell(3).innerHTML= '<input type="text" name="'+'rowDuration'+rowCount+'" value="'+duration.value+'" readonly />';
row.insertCell(4).innerHTML= '<input type="text" name="'+'rowWhen'+rowCount+'" value="'+when.value+'" readonly />';
document.getElementById('medicinename').value='';
document.getElementById('time').value='';
document.getElementById('duration').value='';
document.getElementById('when').value='';
}
function deleteRow(obj) {
var index = obj.parentNode.parentNode.rowIndex;
var table = document.getElementById("myTableData");
table.deleteRow(index);
}
function addTable() {
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border='1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i=0; i<3; i++){
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j=0; j<4; j++){
var td = document.createElement('TD');
td.width='75';
td.appendChild(document.createTextNode("Cell " + i + "," + j));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
In your servlet, use the request.getParameter to access values.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Now, you can get the parameter from input elements using name
String rowMedicine = request.getParameter("rowMedicine1");
//Similarly get the values of all parameters using names
//get the row count
//iterate through it and save it in your database
}

Retrieving multiple Rows from database using javascript and display in an html table

I am trying to display the database values in a html table using javascript but i am getting only the last value in the database table
function productValues() {
if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
var responseJson= JSON.parse(xmlHttp.responseText);
var length=responseJson.a1.length;
document.getElementById("nid").value="";
document.getElementById("pid").value="";
document.getElementById("cid").value="";
document.getElementById("name").value="";
document.getElementById("price").value="";
for(i=0;i<length;i++){
var a=responseJson.a1[i];
var b=responseJson.a2[i];
var c=responseJson.a3[i];
var d=responseJson.a4[i];
var e=responseJson.a5[i];
document.getElementById("nid").value=a;
document.getElementById("pid").value=b;
document.getElementById("cid").value=c;
document.getElementById("name").value=d;
document.getElementById("price").value=e;
}
}
}
//response
ProductSearch prod=new ProductSearch();
prod.setA1(a1);
prod.setA2(a2);
prod.setA3(a3);
prod.setA4(a4);
prod.setA5(a5);
String responseJson = new Gson().toJson(prod);
//html code
</head>
<form id="form1" method="post" action="ProductNameSearchF">
<table align="center">
<tr>
<td><font color="#006400"><b> Select Item:</b></font>
<input type="text" name="searchname" id="user" onclick="clearFields()"/>
<input type="button" id="submit" style=" color:#280000 ;font-size: medium;" value="Edit" onclick="getDetails();" />
<tr>
<br/></td></tr>
<div id="welcometext" align="center">
</div>
</table>
<TABLE cellpadding="8" id ="table" border="1" align="center" style="background-color: #EEEEEE;">
<TR bgcolor="#66CCFF"><font color="#fff">
<TD color="#0080FF" width="0.1%" ><B>Id</B></TD>
<TD color="#0080FF" width="0.5%"><B>ProductType_Id</B></TD>
<TD width="0.1%"><B>Cuisine_Id</B></TD></font>
<TD width="0.5%"><B>Name</B></TD></font>
<TD width="0.5%"><B>Price</B></TD></font>
</TR>
<TR>
<TD><input type="text" name="id" id="nid" style="background-color:transparent; color:blue; " readonly ></TD>
<TD><input type="text" name="productid" id="pid" style="background-color:transparent; color:red; " ></TD>
<TD><b><input type="text" name="cuisineid" id="cid" style="background-color:transparent; color:red; " ></b></TD>
<TD><b><input type="text" name="name" id="name" style="background-color:transparent; color:red; "></b></TD>
<TD><b><input type="text" name="price" id="price" style="background-color:transparent; color:red;" ></b></TD></input>
</TR>
</font>
<font size="+3" color="red"></b>
</font>
<TR>
</tr>
</TABLE>
<table align="center">
<tr>
<td colspan=""> <img src="clear.jpg" width="50" height="30" ></img> <button type="submit" name="someName" value="someValue"><img src="redsubmit.png" width="70" height="30" ></button> </td>
</tr>
</table>
</table>
</form>
Here is my html code , i am adding only the essntial code of the html page
#user3825041: In Html elements id a are unique in nature. I mean if we you repeatedly set same ids with different values, at the end you will have single value(i.e is the last one) updated. Due to which you are getting only last value.
Please try to change ids with each row update.
Or else you can use html table plugins like bootstrap table which are easy and responsive to use. You just need to provide data(JSON/XML format) to these plugins.
http://getbootstrap.com/css/#tables
You can generate table dynamically from javascript, to achieve it your (servlet) response should be like:
ArrayList<ProductSearch> al = new ArrayList<ProductSearch>();
... databse code ...
while(rs.next()) {
ProductSearch prod=new ProductSearch();
prod.setA1(a1);
prod.setA2(a2);
prod.setA3(a3);
prod.setA4(a4);
prod.setA5(a5);
al.add(prod);
}
...
String responseJson = new Gson().toJson(al);
response.getWriter().println(responseJson);
And your html should be like:
<input type="button" value="Show Results" onclick="showTable()" />
<div id="dvTable"></div>
<script type="text/javascript">
function showTable() {
if (xmlHttp.readyState == 4) {
var responseJson = JSON.parse(xmlHttp.responseText);
var table = document.createElement("TABLE");
table.border = "1";
var row = table.insertRow(-1);
var headerCell = document.createElement("TH");
headerCell.innerHTML = "nid";
row.appendChild(headerCell);
var headerCell = document.createElement("TH");
headerCell.innerHTML = "pid";
row.appendChild(headerCell);
var headerCell = document.createElement("TH");
headerCell.innerHTML = "cid";
row.appendChild(headerCell);
var headerCell = document.createElement("TH");
headerCell.innerHTML = "name";
row.appendChild(headerCell);
var headerCell = document.createElement("TH");
headerCell.innerHTML = "price";
row.appendChild(headerCell);
for (var i = 0; i < responseJson.length; i++) {
row = table.insertRow(-1); //creates new row
row.id = "row1"; // if you want to set id of row
var cell = row.insertCell(-1); // creates new column
cell.innerHTML = responseJson[i].a1; // put data in column
cell.id = "column1"; // if you want to set id of column
var cell = row.insertCell(-1);
cell.innerHTML = responseJson[i].a2;
var cell = row.insertCell(-1);
cell.innerHTML = responseJson[i].a3;
var cell = row.insertCell(-1);
cell.innerHTML = responseJson[i].a4;
var cell = row.insertCell(-1);
cell.innerHTML = responseJson[i].a5;
}
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
}
}
</script>

Clone a table row and remove values in JavaScript

I have a set of text inputs fields which I want to be cloned when the user clicks the "add" button. My problem is that the fields are being cloned with the input from the user. Using Javascript, how do I reset the value of the text input fields so they may be cloned without cloning the user input text.
This is my code...
<table width="766" border="0" cellspacing="0" cellpadding="0" id="albumTable">
<tr id="clone">
<td width="230"><input type="text" name="dj_1" /></td>
<td width="230"><input type="text" name="affiliations_1" /></td>
<td width="230"><input type="text" name="rating_1" /></td>
<td width="230"><input type="text" name="comments_1" /><input type="hidden" name="count" value="1" class="count"/></td>
<td width="286" style="position:absolute; top:110px; left: 670px;"><input name="button" type="button" id="Add" value="ADD ROW" onclick="addRow(this.parentNode.parentNode)"></td>
</tr>
</table>
<script type="text/javascript">
function addRow(r){
var root = r.parentNode;
var allRows = root.getElementsByTagName('tr');
var cRow = allRows[0].cloneNode(true)
var cInp = cRow.getElementsByTagName('input');
var countRow = cRow.getElementsByClassName('count');
for(var i=0;i<cInp.length;i++){
cInp[i].setAttribute('name',cInp[i].getAttribute('name').replace(/\d/g,(allRows.length+1)))
}
for(var j=0;j<countRow.length;j++){
countRow[j].setAttribute('value',countRow[j].getAttribute('value').replace(/\d/g,(allRows.length+1)))
}
root.appendChild(cRow);
}
function shownames(){
var allInp=document.getElementsByTagName('input');
for(var i=0;i<allInp.length;i++){
alert(allInp[i].name)
}
}
</script>
Something like this:
var cln = document.getElementByID("clone");
var clns = cln.getElementsByTagName("td");
for(var i = 0; i <clns.length; i++)
{
clns[i].innerHTML = "";
}
In the first for loop, just add this:
cInp[i].value='';

Categories

Resources