www.webdeveloper.com
Results 1 to 15 of 15

Thread: [RESOLVED] Duplicate Multiple Table Rows for Form in Javascript

  1. #1
    Join Date
    May 2010
    Location
    Michigan
    Posts
    9

    resolved [RESOLVED] Duplicate Multiple Table Rows for Form in Javascript

    Hi guys,

    I'm trying to work my way up to being a novice in Javascript but I'm not there quite yet.

    My problem is that I want to create a form in which multiple form fields can be duplicated/deleted upon clicking a button. I have some javascript here that does exactly that, but it will only do it for one table row. This creates a problem since the form I want to duplicate would contain multiple rows.

    I've tried containing everything in a nested table within the duplicatable row. That actually works, but it disables the delete function. Same goes for using a div.

    Here's the Javascript:
    Code:
    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;
    
    				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 vehicles.");
    						break;
    					}
    					table.deleteRow(i);
    					rowCount--;
    					i--;
    				}
    
    			}
    			}catch(e) {
    				alert(e);
    			}
    		}
    And here's the html:
    Code:
    <table id="dataTable" width="760px" border="0" cellpadding="5"  bgcolor="#eeeeee">
    		<tr>
    			<td><input type="checkbox" name="chk"/></td>
    			<td>
    				<select name="Year">
    					<option value="choose">Choose Year</option>
    				</select>
    			</td>
    			<td>
    				<select name="Make">
    					<option value="choose">Choose Division</option>
    				</select>
    			</td>
    			<td>
    				<select name="Model">
    					<option value="choose">Choose Model</option>
    				</select>
    			</td>
    			<td>
    				<select name="Body">
    					<option value="choose">Choose Body</option>
    				</select>
    			</td>
    			<td>
    				<select name="Trim">
    					<option value="choose">Choose Trim</option>
    				</select>
    			</td>
    		</tr>
    		<tr>
    		<td>
    		What about me?
    		</td>
    		</tr>
    	</table>
    I've been driving myself nuts with this all day. Can anyone help me out?

    Thanks for checking it out.

  2. #2
    Join Date
    May 2010
    Location
    Michigan
    Posts
    9
    Hmmm... still having trouble with it. Anybody got any ideas?

  3. #3
    Join Date
    Dec 2003
    Location
    Bucharest, ROMANIA
    Posts
    15,428
    Here's a basic example of adding rows using cloneNode() method. It can be extended to delete rows, as well, if needed.
    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <title>Untitled Document</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta http-equiv="Content-Style-Type" content="text/css">
    <meta http-equiv="Content-Script-Type" content="text/javascript">
    <style type="text/css">
    #mytable{
    border:0;
    border-collapse:collapse;
    }
    #mytable td{
    height:50px;
    width:200px;
    text-align:center;
    }
    .one{
    background:#ccc;
    }
    .two{
    background:#e6e6e6;
    }
    </style>
    <script type="text/javascript">
    var clone;
    var isIE=/*@cc_on!@*/false;//IE detector
    function addRow(){
    var tbody=document.getElementById('mytable').getElementsByTagName('tbody')[0];
    tbody.appendChild(clone);
    cloneRow();
    
    }
    function cloneRow(){
    var rows=document.getElementById('mytable').getElementsByTagName('tr');
    var index=rows.length+1;
    clone=rows[rows.length-1].cloneNode(true);
    clone.className=index&#37;2==0?'two':'one';
    var inputs=clone.getElementsByTagName('input'), inp, i=0;
    while(inp=inputs[i++]){
    inp.name=inp.name.replace(/\d{1,}/g,index);
    if(isIE){ // solve for IE "new name in DOM bug"
    document.forms['myform'].elements[inp.name]=inp;
    }
    }
    }
    onload=cloneRow
    </script>
    </head>
    <body>
    <form id="myform" name="myform" action="">
    <table id="mytable">
    <tbody>
    <tr class="one">
    <td><input name="number1"></td>
    <td><input name="title1"></td>
    <td><input name="address1"></td>
    <td><input name="zipcode1"></td>
    </tr>
    </tbody>
    </table>
    <br>
    <input type="button" value="Add A Row" onclick="addRow()">
    </form>
    </body>
    </html>

  4. #4
    Join Date
    May 2010
    Location
    Michigan
    Posts
    9
    Thanks Kor! That helped!

  5. #5
    Join Date
    Mar 2011
    Posts
    11
    Why does this add row in the second last row of the table?
    I was seeing this example, but was unable to find out that how should i apply it so that it adds rows to end of the table.

  6. #6
    Join Date
    Dec 2003
    Location
    Bucharest, ROMANIA
    Posts
    15,428
    Quote Originally Posted by tweety.scorpion View Post
    Why does this add row in the second last row of the table?
    I was seeing this example, but was unable to find out that how should i apply it so that it adds rows to end of the table.
    But it adds the row at the end of the table. There is no other end I don't understand your question.

  7. #7
    Join Date
    Mar 2011
    Posts
    11
    To be more clear :

    here is my code :

    this is my javascript
    Code:
    <script type="text/javascript">
    // cloning rows
    
    var clone;
    
    function addRow(){
    var tb=document.getElementById('ListTable').getElementsByTagName('tbody')[0];
    
    cloneRow();
    tb.appendChild(clone);
    }
    function cloneRow(){
    var rows=document.getElementById('ListTable').getElementsByTagName('tr');
    var index=rows.length+1;
    clone=rows[rows.length-1].cloneNode(true);
    var inputs=clone.getElementsByTagName('input'), inp, i=0;
    while(inp=inputs[i++] ){
    inp.name=inp.name.replace(/\d{1,}/g,index);
    
    }
    
    var selects=clone.getElementsByTagName('select'), sel, j=0;
    while(sel=selects[i++] ){
    sel.name=sel.name.replace(/\d{1,}/g,index);
    
    }
    }
    onload=cloneRow
    </script>

    here is my table

    Code:
      <table width="302" border="1" id="ListTable">
        <caption>
          List All Waste Removed :
        </caption>
        <tr>
          <th width="85" scope="col">CATEGORIES</th>
          <th width="88" scope="col">SubCategory</th>
          <th width="107" scope="col">TOTAL </th>
        </tr>
         <tbody>
        <tr>
          <td><select name="Category" id="Category">
            <option disabled="disabled" selected="selected">Select Category</option>
            <?php
    			$categories = mysql_query("SELECT * FROM univ_category ORDER BY UC_Name ASC");
    			while($Category = mysql_fetch_assoc($categories)) {
    				echo"<option value=\"{$Category['UC_ID']}\">{$Category['UC_Name']}</option>";
    				
    			}
    			?>
          </select></td>
          <td><select name="subcategories" id="subcategories">
          </select></td>
          <td><input name="quantity" type="text" id="quantity" value="" title="Type Quantity"  /></td>
          </tr>
        </tbody>
      </table>
    
      <input type="button" value="Add A Row" onClick="addRow()">

    The problem I am getting is that when i click Add row, it adds row to the front of last row as it is cloning the last row.

    I would like it to add row at the end of table.

  8. #8
    Join Date
    Dec 2003
    Location
    Bucharest, ROMANIA
    Posts
    15,428
    You have formatted wrong the TABLE element. Even you don't write it explicitly, the TBODY exists. A table can have a lot of TBODYs, but if you fragment only a part of the TABLE with a TBODY, the interpreter of the browser will consider it as the second one (the first, as I said, is implicit, and it is considered to wrap all the rows which are not already wrapped in the other TBODY))
    Thus, you wrote:

    table
    tr ... /tr
    tbody
    tr ... /tr
    /tbody
    /table

    But the browser's interpreter will see this:

    table
    tbody
    tr ... /tr
    /tbody
    tbody
    tr ... /tr
    /tbody
    /table

    According to your table's structure, you should change the code like:
    Code:
    var tb=document.getElementById('ListTable').getElementsByTagName('tbody')[1];
    Last edited by Kor; 03-17-2011 at 11:39 AM.

  9. #9
    Join Date
    Mar 2011
    Posts
    11
    Thank you so much Mr. Kor.
    It really worked.. I spent like 5 hrs figuring out where was i wrong.
    U saved me. Thanks

  10. #10
    Join Date
    Mar 2011
    Posts
    11
    Hi Kor

    I was using your code , for cloning and i just realized that when i input some value in the text box and then hit the add row button ..it is actually copying the value inside the text box and cloning it too.
    is there a way that i can clone the row but reset the values of input text box?

    Also I want to understand what does this means :

    inp.name=inp.name.replace(/\d{1,}/g,index);
    Last edited by tweety.scorpion; 03-24-2011 at 11:14 AM.

  11. #11
    Join Date
    Dec 2003
    Location
    Bucharest, ROMANIA
    Posts
    15,428
    Quote Originally Posted by tweety.scorpion View Post
    Hi Kor

    I was using your code , for cloning and i just realized that when i input some value in the text box and then hit the add row button ..it is actually copying the value inside the text box and cloning it too.
    is there a way that i can clone the row but reset the values of input text box?
    They are always reset, because the cloning is made before any changes are possible. Or, have you change something?
    Quote Originally Posted by tweety.scorpion View Post
    Also I want to understand what does this means :

    inp.name=inp.name.replace(/\d{1,}/g,index);
    increments the names of the elements, in case it is needed. For instance, in an input on the first row has the name="address1", the cloned input on next row will get the name="address2", and so on.

  12. #12
    Join Date
    Mar 2011
    Posts
    11
    thanks for the explanation
    Last edited by tweety.scorpion; 03-24-2011 at 12:36 PM.

  13. #13
    Join Date
    Mar 2011
    Posts
    11
    Thanks..I got it..
    i used clonerow() before..
    Last edited by tweety.scorpion; 03-24-2011 at 12:35 PM.

  14. #14
    Join Date
    Mar 2011
    Posts
    11

    Validation on cloned rows

    Hi

    How do you put validation controls in cloned rows?
    They work for the first row..but they don't work for other rows..

    I used your cloning method.
    Help would be appreciated.

    I am doing something like this :

    if($('#Category').val() == 0) {
    errors = true;
    error_message += 'Please select a Category.\r\n';
    }
    but when i clone the row (Add new rows) , validation does not works.

  15. #15
    Join Date
    Dec 2003
    Location
    Bucharest, ROMANIA
    Posts
    15,428
    Quote Originally Posted by tweety.scorpion View Post
    Hi

    How do you put validation controls in cloned rows?
    They work for the first row..but they don't work for other rows..

    I used your cloning method.
    Help would be appreciated.

    I am doing something like this :

    if($('#Category').val() == 0) {
    errors = true;
    error_message += 'Please select a Category.\r\n';
    }
    but when i clone the row (Add new rows) , validation does not works.
    What is that: $('#Category').val()? JQuery? Don't use JQuery (nor any other JavaScript llybrary) till you haven't learned enough JavaScript language.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles