简体   繁体   中英

Insert HTML table row clone at index without jquery

I am attempting to insert a row at the index of the addmorebutton td row.

First attempt indeed adds a row at the desired index however not as I would have expected, simply as space vs actually adding a bounded row column box.

How do I insert a new row at the clicked index of td that is empty and is indeed apart of the table?

 function deleteRow(row) { var i = row.parentNode.parentNode.rowIndex; document.getElementById('Table').deleteRow(i); } function addRow() { var i = row.parentNode.parentNode.rowIndex; document.getElementByID('Table').insertRow(i); } turkSetAssignmentID(); 
 <script type='text/javascript' src='https://s3.amazonaws.com/mturk-public/externalHIT_v1.js'></script> <form name='mturk_form' method='post' id='mturk_form' action='https://www.mturk.com/mturk/externalSubmit'> <input type='hidden' value='' name='assignmentId' id='assignmentId' /> <h1>This is a test</h1> <div id="tablediv"> <input type="button" id="addbutton" value="Add Index" /><br/><br/> <table id="Table" border="1"> <tr> <td>Index</td> <td>Measured Depth</td> <td>Inclination</td> <td>Azimuth</td> <td>Delete?</td> <td>Add Row?</td> </tr> <tr> <td>1</td> <td><input size=25 type="text" id="Measured Depth" contenteditable='true'></td> <td><input size=25 type="text" id="Inclination" contenteditable='true'></td> <td><input size=25 type="text" id="Azimuth" contenteditable='true'></td> <td><input type="button" id="delbutton" value="Delete" onclick="deleteRow(this)" /></td> <td><input type="button" id="addmorebutton" value="Add More Indexs" onclick="addRow.apply(this)" /></td> </tr> </table> </div> <p><input type='submit' id='submitButton' value='Submit' /></p> </form> 

You could try to add the respective cells to new row, saving the row on a var and the with the appendChild() function. Something like this:

 function addRow(row) { var i = row.parentNode.parentNode.rowIndex + 1; var nextRow = document.getElementById('Table').insertRow(i); // Start iterating over all the cells on the row var cell = nextRow.insertCell(0); cell.appendChild(document.createTextNode(i)); cell = nextRow.insertCell(); cell = nextRow.insertCell(); cell = nextRow.insertCell(); cell = nextRow.insertCell(); cell = nextRow.insertCell(); input = document.createElement("Input"); input.type = "button"; input.setAttribute("onclick", "addRow(this)"); input.value = "Add More Indexs" cell.appendChild(input); } 

And of course append on each cell the respective input. Then maybe you would like to add a function to increase the index number of the rows under the new one...

Also I changed the onclick value on the original button to addRow(this) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM