I'm pretty junior, so I'm unsure on if I worded the question properly.
I'm looking to create a textbox in HTML where the user can input the amount of columns and rows for the table. From there I need to use Javascript/Jquery to create the table when the button is clicked.
So far I have been able to create the text boxes. I capture the inputed numbers into variables, and created two for loops.
It doesn't work... :/
<body>
Set Rows:<br>
<input type="text" id="setRows">
<br>
Set Columns:<br>
<input type="text" id="setColumns">
<button type='button' onclick='myForm()'>Create Table</button>
<p id = "demo1"></p>
<p id = "demo2"></p>
</body>
function myForm()
{
var setRows = document.getElementById("setRows").value;
//document.getElementById("demo1").innerHTML = setRows;
var setColumns = document.getElementById("setColumns").value;
//document.getElementById("demo2").innerHTML = setColumns;
}
$(document).ready(function()
{
$("button").click(function()
{
$("<table></table>").insertAfter("p:last");
for (i = 0; i < setRows; i++)
{
$("<tr></tr>").appendTo("table");
}
for (i = 0; i < setColumns; i++)
{
$("<td>column</td>").appendTo("tr");
}
});
});
The main problem is that you're setting the variables setRows and setColumns in a different function from the one that uses them. You should do everything in one function -- either bind it with the onclick attribute or with $("button").click() -- rather than splitting it into separate functions.
I also think it would be clearer to use nested loops to make it more obvious that you're adding cells to each row. appendTo() will automatically clone the object being appended if there are multiple targets, but this is an obscure feature (I'm very experienced with jQuery and didn't know about it until now) that isn't so obvious. It will also make the code easier to extend if you need to put different values in each cell (e.g. filling them from an array of data, or initializing with something like "row I col J").
function myForm() {
var setRows = $("#setRows").val();
var setColumns = $("#setColumns").val();
var table = $("<table>").insertAfter("p:last");
for (var i = 0; i < setRows; i++) {
var row = $("<tr>");
for (var j = 0; j < setColumns; j++) {
$("<td>column</td>").appendTo(row);
}
table.append(row);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Set Rows:<br>
<input type="text" id="setRows">
<br>
Set Columns:<br>
<input type="text" id="setColumns">
<button type='button' onclick='myForm()'>Create Table</button>
<p id = "demo1"></p>
<p id = "demo2"></p>
jsBin demo
<button type='button'>Create Table</button>
It's quite slow to append elements inside a for loop,
instead create a HTML representation of your table, and append it only once you're done generating it:
$("button").click(function(){
var setRows = +$("#setRows").val(); // Value to Number using Unary +
var setColumns = +$("#setColumns").val();
// THE HTML STRING
var table = "<table>";
// OUTER FOR LOOP : ROWS
for (var i=0; i<setRows; i++){
// START THE TR
table += "<tr>";
// INNER FOR LOOP :: CELLS INSIDE THE TR
for (var j = 0; j < setColumns; j++) {
table += "<td>column</td>";
}
// CLOSE THE TR
table += "</tr>";
}
// CLOSE THE TABLE
table += "</table>";
// APPEND ONLY ONCE
$("p:last").after(table);
});
As you see above I've used a for loop inside another for loop cause:
<tr> <!-- OUTER FOR LOOP (rows) -->
<td>column</td><td>column</td> <!-- INNER FOR LOOP (cells) -->
</tr>
This would work:
$(document).ready(function(){
$("#myBtn").click(function(){
var setRows = $('#setRows').val(); // get your variables inside the click handler so they are available within the scope of your function
var setColumns = $('#setColumns').val();
var rows=[]; // create an array to hold the rows
for (var r = 0; r < setRows; r++){ // run a loop creating each row
var cols=[]; // create an array to hold the cells
for (var c = 0; c < setColumns; c++){// run a loop creating each cell
cols.push('<td>column</td>'); // push each cell into our array
}
rows.push('<tr>'+cols.join('')+'</tr>'); // join the cells array to create this row
}
$('<table>'+rows.join('')+'</table>').insertAfter("p:last"); // join all of the rows, wrap in a table tag, then add to page
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Set Rows:<br>
<input type="text" id="setRows" value="4"/>
<br>
Set Columns:<br>
<input type="text" id="setColumns" value="5"/>
<button type="button" id="myBtn" >Create Table</button>
<p id = "demo1"></p>
<p id = "demo2"></p>
You have to use a nested loop (as others have suggested).
Also when creating elements using jQuery - you don't have to specify both opening and closing tags - $("<elem />") works nicely..
Snippet:
$(function () {
var go = $("#go");
var cols = $("#columns");
var rows = $("#rows")
go.click(function () {
var numRows = rows.val();
var numCols = cols.val();
var table = $("<table />");
var head = $("<thead />");
var row = $("<tr />");
// build header
var headRow = row.clone();
for (var i = 0; i < numCols; i++) {
var th = $("<th />");
th.append(i);
headRow.append(th);
}
table.append(headRow);
// build table
for (var j = 0; j < numRows; j++) {
var addRow = row.clone();
for (var k = 0; k < numCols; k++) {
var cell = $('<td />');
cell.css({"border":"solid 2px teal"});
cell.append("<p>R:" + j + " |C:" + k + "</p>");
addRow.append(cell);
}
table.append(addRow);
}
$('body').append(table);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label>Rows:</label>
<input id="rows" />
<label>Columns:</label>
<input id="columns" />
<button id="go">Go!</button>
Your variables are created in a function (setRows and setColumns), so they are not available outside of this function. Define them globally if you want the "myForm" function to remain (it's not needed though).
Check this quick example, keeping your code intact:
var setRows = 0;
var setColumns = 0;
function myForm() {
//setRows = document.getElementById("setRows").value;
setRows = $('#setRows').val();
//setColumns = document.getElementById("setColumns").value;
setColumns = $('#setColumns').val();
}
$(document).ready(function() {
$("button").click(function() {
$("<table></table>").insertAfter("p:last");
for (i = 0; i < setRows; i++) {
$("<tr></tr>").appendTo("table");
}
for (i = 0; i < setColumns; i++) {
$("<td>column</td>").appendTo("tr");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Set Rows:
<br>
<input type="text" id="setRows">
<br>Set Columns:
<br>
<input type="text" id="setColumns">
<button type='button' onclick='myForm();'>Create Table</button>
<p id="demo1"></p>
<p id="demo2"></p>
A few pointers going forward:
You can skip the "myForm" function, and instead put your variables just inside the ready-function.
You're also binding "button" to two things: to run myForm and to create your table. Removing the myForm-function, like stated above, obviously means you can remove the "onclick" event. But even if you keep the function, the call to "myForm" would be better placed inside the ready-function.
Related
In my assignment i have to take the data from user input using and save data in local storage. I have to print this data from local storage in horizontal table format to other pages.For this i made the code for user input and saving data in local storage
<style>
data {
color: #138bc2;
}
</style>
<body>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
<div id="POItablediv">
<p>
<input type="button" id="bt" value="Submit Data" onclick="submit()" />
</p>
<input type="button" onclick="insRow()" id="addPOIbutton" value="Add values"/><br/><br/>
<table id="POITable" border="1">
<thead>
<tr>
<td>WEEK NO</td>
<td>Daily exercise</td>
<td>calorie</td>
<td>food</td>
<td>Revision no</td>
<td>Delete?</td>
</tr>
</thead>
<tbody>
<tr>
<td><input size=25 type="text" id="weekbox"/></td>
<td><input size=25 type="text" id="latbox"/></td>
<td><input size=25 type="text" id="lngbox"/></td>
<td><input size=25 type="text" id="lnbox"/></td>
<td><input size=25 type="text" id="lntbox"/></td>
<td><input type="button" id="delPOIbutton" value="Delete" onclick="deleteRow(this)"/></td>
</tr>
<tbody>
</table>
</body>
<script>
function deleteRow(row)
{
var i=row.parentNode.parentNode.rowIndex;
if(i>1){
document.getElementById('POITable').deleteRow(i);
}
}
function insRow()
{
var x=document.getElementById('POITable');
var new_row = x.rows[1].cloneNode(true);
var len = x.rows.length;
new_row.cells[0].childNodes[0].value = "";
var inp1 = new_row.cells[1].getElementsByTagName('input')[0];
inp1.id += len;
inp1.value = '';
var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
inp2.id += len;
inp2.value = '';
x.appendChild( new_row );
var inp3 = new_row.cells[3].getElementsByTagName('input')[0];
inp3.id += len;
inp3.value = '';
var inp4 = new_row.cells[4].getElementsByTagName('input')[0];
inp4.id += len;
inp4.value = '';
x.appendChild( new_row );
}
function submit()
{
var table = document.getElementById("POITable")
var tableLen = table.rows.length
var data = {labels: [], alpha: [], beta: [],gamma:[]}
for (var i = 1; i < tableLen; i++)
{
data.labels.push(table.rows[i].cells[0].childNodes[0].value)
data.alpha.push(table.rows[i].cells[1].childNodes[0].value)
data.beta.push(table.rows[i].cells[2].childNodes[0].value)
data.gamma.push(table.rows[i].cells[3].childNodes[0].value)
}
var alphadata = data
localStorage.setItem("quant", JSON.stringify(alphadata));
above code is for taking input from user and saved in local storage .My aim is to print data from local storage to another page in vertical header I mean that the table has the header () tag on the left side (generally).
e<body>
<input type="button" onclick="CreateTableFromJSON()" value="Create Table From JSON" />
<p id="showData"></p>
</body>
<script>
function CreateTableFromJSON() {
var myBooks =JSON.parse(localStorage.getItem("quant"));
var col = [];
for (var i = 0; i < myBooks.length; i++) {
for (var key in myBooks[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
// CREATE DYNAMIC TABLE.
var table = document.createElement("table");
// CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
var tr = table.insertRow(-1); // TABLE ROW.
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th"); // TABLE HEADER.
th.innerHTML = col[i];
tr.appendChild(th);
}
// ADD JSON DATA TO THE TABLE AS ROWS.
for (var i = 0; i < myBooks.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = myBooks[i][col[j]];
}
}
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
</script>
</html>
Table is not printing when i click on button in second page . its gives me blank page . Any lead would be appreciated.
This code implements another function to create a horizontal format.
Please read the comments and also try to understand it so that it can help you in the future
<html>
<body>
<input type="button" onclick="createHorizontal()" value="Create Table From JSON" />
<p id="showData"></p>
<div id="horizontal"></div>
</body>
<script>
function createHorizontal(){
var myBooks = JSON.parse(localStorage.getItem("quant"));
console.log(myBooks);
col_keys = Object.keys(myBooks);
// Object.keys gets the keys of the object
col_values = Object.values(myBooks);
// Object.values gets the values in an object
var final_array = [];
/* Here is the final array that will hold all the data */
for(var i = 0; i < col_keys.length; i++){
var inner = [];
// The inner array that will be pushed with a new value
// after every loop
inner.push("<div class='main'>");
inner.push("<li>" + col_keys[i] + "</li>");
for(var j = 0; j < col_values[0].length; j++){
inner.push("<li>" + col_values[i][j] + "</li>");
}
inner.push("</div>");
//The above code creates the html for each of the rows
inner = inner.join("");
// To remove the commas from the final array
final_array.push(inner);
}
console.log(final_array);
var elem = document.getElementById("horizontal");
var final_div = [];
final_div.push("<div class='container'>");
for(var n = 0; n < final_array.length; n++){
final_div.push(final_array[n]);
}
final_div.push("</div>");
// The above code creates the html for the whole div block
final_div = final_div.join("");
// To remove the commas
console.log(final_div);
elem.innerHTML = "";
elem.innerHTML = final_div;
}
</script>
<style>
.container {
display: flex;
flex-direction: column;
/* Make the rows stack on top of each other */
}
.main {
display: flex;
flex-direction: row;
/* Make the elements in the div stack side by side */
}
.main li {
list-style-type: none;
padding: 5px 10px;
width: 50px;
}
.main li:first-of-type {
font-weight: bold;
background-color: #222222;
color: #ffffff;
}
</style>
</html>
It also uses CSS to make the elements appear in that format or else it would look different. I advise you to analyze and understand it.
So I did not find a problem with the first file that inserts the JSON data to the local storage. The problem was with getting the data from the second file
<html>
<body>
<input type="button" onclick="CreateTableFromJSON()" value="Create Table From JSON" />
<p id="showData"></p>
</body>
<script>
function CreateTableFromJSON() {
var myBooks = JSON.parse(localStorage.getItem("quant"));
console.log(myBooks);
/* This logs the object to confirm whether it is there and to
confirm the values inside it You should make this a habit
so that you can check for errors*/
// var col = [];
// for (var i = 0; i < myBooks.length; i++) {
// for (var key in myBooks[i]) {
// if (col.indexOf(key) == -1) {
// col.push(key);
// }
// }
// }
/* The code above is the one I have commented out and replaced with
the one below to get both the keys and values in separate arrays */
col_keys = Object.keys(myBooks);
// Object.keys gets the keys of the object
col_values = Object.values(myBooks);
// Object.values gets the values in an object
// CREATE DYNAMIC TABLE.
var table = document.createElement("table");
// CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
var tr = table.insertRow(-1); // TABLE ROW.
/* --- REFERENCE 1 --- The length of col_keys and col_values is the same because they
are key and value pairs */
for (var i = 0; i < col_keys.length; i++) {
var th = document.createElement("th"); // TABLE HEADER.
th.innerHTML = col_keys[i];
/* col_keys has the keys of the object which are added to
the table header */
tr.appendChild(th);
}
// ADD JSON DATA TO THE TABLE AS ROWS.
for (var i = 0; i < col_values[0].length; i++) {
/* The loop runs as many times as the number of items in each array
EXPLANATION: col_values contains arrays.
col_values[0].length returns the length of the first array, which is
the array that contains the labels.
And since all the arrays have the same length whether they have a value
or not, the length of the first array is the same for all the others.
--- REFERENCE 2 --- In this case this outer loop runs 2 times*/
tr = table.insertRow(-1);
for (var j = 0; j < col_values.length; j++) {
/* The inner loop runs as many times as the number of key-value pairs
in the object.
EXPLANATION: As " --- REFERENCE 1 --- " above says, this will run **4** times
based on your current object which has:
1.labels
2.alpha
3.beta
4.gamma
*/
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = col_values[j][i];
/* Each time the loop runs, it inserts the "i" value of the array
of each of the values of the object.
Check " --- REFERENCE 2 --- " ... since "i" is less than the length
of each array, it will only run as many times as the number of values
in the array.
In this case **2** times.
*/
}
}
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
</script>
</html>
There are comments everywhere so make sure to read them and understand why it works that way. Because this is also a learning process. If you have a question just ask.
I am trying to understand the insertion sort algorithm. I want to use an input button and diagram. When the user writes a number then click the button, my page will create random values. I found some snippets on the internet but they use i = 0. I want to use my input value instead of i = 0. How can I do it?
A part of my index.html:
<div id="buttons">
<a class="button" id="butonInsert" href="javascript://">insertion sort</a>
<a class="button" id="butonReset" href="javascript://">Reset</a>
<input type="number" id="myNumber" value="blabla">
<button onclick="reset()"></button>
A part of my script.js:
function reset() {
for (i=0; i<50; ++i) {
data[i] = ~~(i*160/50);
}
for (i=data.length-1; i>=0; --i) {
var ridx = ~~( Math.random() * ( data.length ) );
data.swap(i, ridx);
}
var tb = $("#sortPanel");
tb.empty();
var tr = $("<tr></tr>");
for (i=0; i<data.length; ++i) {
tr.append("<td id='b"+i+"'>" +
"<div class='cc' style='height: "+data[i]+"px;'>" +
"</div></td>");
}
tb.append(tr);
resetted = true;
}
I didn't quite understand what you are trying to do but if you just want to use an input's value you can easily get it with javascript and use it instead of i=0.
var inputValue = document.getElementById("myNumber").value ;
Then in your for statements :
for (var i = inputValue ; i < data.length; ++i) {
// code
}
Use document.getElementbyId('myNumber').value. This might work.
So i have a script like this to make a 2x2 table by javascript
function createtable(){
var tbl = document.getElementById('x');
if (tbl.contains()==false){
tbl.setAttribute('border', '1');
var tbdy = document.createElement('tbody');
for (var i = 0; i < 2; i++) {
var tr = document.createElement('tr');
for (var j = 0; j < 2; j++) {
var td = document.createElement('td');
tr.appendChild(td);
td.style.height='50px';
td.style.width='50px';
}
tbdy.appendChild(tr);
}
tbl.appendChild(tbdy);
}
<form>
<input type="button" value="Create Table" onclick="createtable()"> <br>
</form>
<table id="x"> </table>
I want to check if table x contains anything or not to create itself. Im trying to use the contains() to check but it doesnt work.
You can check the number of rows in the table:
var x = document.getElementById("myTable").rows.length;
See reference here: https://www.w3schools.com/jsref/coll_table_rows.asp
Using this:
var tbl = document.getElementById('x');
if (tbl.rows.length == 0) {
// empty
}
If you want to check if there are any inside table do this
document.getElementById("myTable").rows.length
More info here
you can Check the Row Counts
var tbl = document.getElementById('x');
if(tbl.rows.length==0){
}
if the tbl.rows.length is 0 that means the table don't have any rows
There are multiple ways. One of way, you can use childElementCount property.
if (tbl.childElementCount==0)
{
}
For more details you can refere link
In this case, since there are no child elements or text nodes in your table, you can just check to see if the innerHTML property is falsy. This prevents your createtable function from appending additional children after the function has been run once. For example:
function createtable() {
var tbl = document.getElementById('x');
if (!tbl.innerHTML) {
var tbdy = document.createElement('tbody');
tbl.setAttribute('border', '1');
for (var i = 0; i < 2; i++) {
var tr = document.createElement('tr');
for (var j = 0; j < 2; j++) {
var td = document.createElement('td');
tr.appendChild(td);
td.style.height = '50px';
td.style.width = '50px';
}
tbdy.appendChild(tr);
}
tbl.appendChild(tbdy);
}
}
<form>
<input type="button" value="Create Table" onclick="createtable()">
<br>
</form>
<table id="x"></table>
Plain javascript:
!![].length
or use Lodash
_.head([]);
// => undefined
I want the user to enter a number then when it is submitted, it is inserted into the array totalBags.
The user can then submit another number, when submitted the array elements are added together.
E.g. Input = 2
Press submit
Output = 2
New input = 3
Press submit
Output = 5
Here is my code:
<html>
<head>
<script type = "text/javascript">
function submitOrder()
{
var allBags = [];
var bags_text = document.getElementById("bags").value;
allBags.push(bags_text);
var totalBags = 0;
for (var i = 0; i < allBags.length; i++)
{
totalBags += allBags[i]; // here is the problem... i think
}
document.getElementById("container").innerHTML = "<p>"+totalBags+"</p><input type=\"reset\" value=\"New Order\" onClick=\"resetOrder()\" />";
}
function resetOrder()
{
document.getElementById("container").innerHTML = "<p><label for=\"bags\">No. bags: </label><input type=\"text\" id=\"bags\" /></p><p><input type=\"button\" value=\"Subit order\" onClick=\"submitOrder()\"> <input type=\"reset\" value=\"Reset Form\" /></p>";
}
</script>
</head>
<body>
<form name="order_form" id="order_form">
<div id="container">
<label>Total bags: </label><input id="bags" type="text" ><br>
<input type="button" id="submitButton" value="Subit order" onClick="submitOrder()">
<input type="reset" value="Reset" class="reset" />
</div>
</form>
</html>
I should rewrite the program a bit. First, you can define global variables which won't be instantiated in the function. You are doing that, which resets the variables. Fe
function submitOrder()
{
var allBags = [];
// ...
}
It means that each time you're clicking on the button allBags is created as a new array. Then you add an value from the input element. The result is that you have always an array with one element. It's best to declare it outside the function. By this, you ensure that the variables are kept.
// general variables
var allBags = [];
var totalBags = 0;
function submitOrder()
{
// the result is a string. You have to cast it to an int to ensure that it's numeric
var bags_text = parseInt(document.getElementById("bags").value, 10);
// add result to allBags
allBags.push(bags_text);
// total bags
totalBags += bags_text;
// display the result
document.getElementById("container").innerHTML = "<p>"+totalBags+"</p><input type=\"reset\" value=\"New Order\" onClick=\"resetOrder()\" />";
}
by leaving out the loop, you have an more performant program. But don't forget to clear the array and the totalBags variable to 0 if you're using the reset button.
function resetOrder()
{
document.getElementById("container").innerHTML = "...";
// reset variables
totalBags = 0;
allBags = [];
}
Try to use:
for (var i = 0; i < allBags.length; i++)
{
totalBags += parseInt(allBags[i],10);
}
Or use Number(allBags[i]) if you prefer that.
Your element allBags[i] is a string and + between strings and concatenting them.
Further study: What is the difference between parseInt(string) and Number(string) in JavaScript?
function submitOrder()
{
var allBags = parseInt(document.getElementById("bags").value.split(""),10);//Number can also used
var totalBags = 0;
for (var i = 0; i < allBags.length; i++)
{
totalBags += allBags[i];
}
document.getElementById("container").innerHTML = "<p>"+totalBags+"</p><input type=\"reset\" value=\"New Order\" onClick=\"resetOrder()\" />";
}
I am creating a form and I have a field set for client information and the ability to add another field set for another client if needed.
As of now the additional field sets' field id adds by 1 which is good, but I would like for each of the fields in the field set to add by 1 as well.
var _counter = 0;
function Add() {
_counter++;
var oClone = document.getElementById("client1").cloneNode(true);
oClone.id += (_counter + "");
document.getElementById("placehere").appendChild(oClone);
Here's a page that clones and increments the fieldset as well as any children elements within the set. It's assuming that both fieldset and children inputs have a numeric suffix. i.e. fieldset1 and textfield2, etc.
Cheers.
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
// store a reference to the last clone so I can increment off that.
window.lastClone = null;
function incrementId(id) {
// regexp is looking for text with a number suffix. adjust accordingly.
var numberSuffixRegExp = /(.*?)(\d*)$/;
var regExpMatch = numberSuffixRegExp.exec(id);
// assuming a match will be made here, and position 1 and 2 are populated.
var prefix = regExpMatch[1];
var counter = parseInt(regExpMatch[2]);
counter++;
return prefix + counter;
}
function cloneFieldSet() {
if (!window.lastClone) {
window.lastClone = 'fieldset1';
}
var newFieldSet = document.getElementById(lastClone).cloneNode(true);
newFieldSet.id = incrementId(newFieldSet.id);
var tagNames = ['input', 'select', 'textarea']; // insert other tag names here
var elements = [];
for (var i in tagNames) {
// find all fields for each tag name.
var fields = newFieldSet.getElementsByTagName(tagNames[i]);
for(var k = 0; k < fields.length; k++){
elements.push(fields[k]);
}
}
for (var j in elements) {
// increment the id for each child element
elements[j].id = incrementId(elements[j].id);
}
document.getElementById("placehere").appendChild(newFieldSet);
window.lastClone = newFieldSet.id;
}
</script>
</head>
<body>
<input type='button' value='Clone' onclick='cloneFieldSet()'/><br/>
<fieldset id='fieldset1'>
<table>
<tr>
<td>Label One:</td>
<td><input type='text' id='fieldOne1'/></td>
</tr>
<tr>
<td>Label Two:</td>
<td><input type='text' id='fieldTwo1'/></td>
</tr>
<tr>
<td>Label Three:</td>
<td><select id='selectOne1'>
<option>Some Value</option>
</select></td>
</tr>
</table>
</fieldset>
<div id='placehere' style='margin:10px 0; border:1px solid black'>
</div>
</body>
</html>
Try This : It only adds an updated id to user input form elements.
If you want to updated all child elements in the fieldset, remove the if statement :)
var _counter = 0, _fcounter = 0;
function add(){
var i, j,
oClone = document.getElementById("client1").cloneNode(true),
fldTypes = "INPUT SELECT TEXTAREA CHECKBOX RADIO",
fields = oClone.children;
_counter++;
oClone.id += (_counter + "");
for(i=0, j= fields.length; i<j; i++){
if(fldTypes.indexOf(fields[i].nodeName) > -1){ //checks for user input form elements
_fcounter ++;
fields[i].id += (_fcounter + "");
}
}
document.getElementById("placehere").appendChild(oClone);
return oClone;
}
See Example: http://jsfiddle.net/yfn6u/8/