Now I will share a simple script how to Add and Remove table row by javascript.
exactly it was my problem before, it made me very confused because sometime when it work, it removed wrong row, so oh god . . .
But now I have fixed it.
I have a table with some task,
When we click delete button, it will delete the right row and if we click add button it will automatically add new row on the last of table.
Look for the script below :
#javascript
<script type="text/javascript">
function remove(id){
// initial variable
var table = document.getElementById('schedule'); // get table id
var rows = table.getElementsByTagName('tr'); // get all table rows
var target = id; // row will remove
var j = 1;
for(i=0;i<rows.length;i++,j++){
if(rows[i].id==target){
table.deleteRow(i);
i--;
}else{
j--;
}
}
}
function add(){
var table = document.getElementById('schedule'); // get table id
var lastRow = table.getElementsByTagName('tr').length; // get last row
var newId = lastRow+1; // make new id
var row = document.getElementById('schedule').insertRow(lastRow); // create row
row.setAttribute('id','task'+newId); // insert row id
var cell0 = row.insertCell(0);// create cell 1
var cell1 = row.insertCell(1);// create cell 2
cell0.innerHTML = 'Task '+newId+' - Default'; // insert data cell 1
cell1.innerHTML = '<a style="cursor:pointer;" onClick="remove(\'task'+newId+'\');" >X</a>';// insert data cell 2
}
</script>
#HTML script
<table cellpadding="0" cellspacing="0" width="300" border="1" id="schedule">
<?php
for($i=1; $i<5; $i++){
?>
<tr id="task<?php echo $i; ?>">
<td>Task <?php echo $i; ?> - Default</td>
<td><a style="cursor:pointer;" onClick="remove('task<?php echo $i; ?>');" >X</a></td>
</tr>
<?php
}
?>
</table>
<input type="button" onClick="add();" value="add" />
Hope it useful for all, if you have question, just write your comment below.
Good luck :)

Very helpful,
ReplyDeleteI search this tutorial,
Thank you Bayu..
You are welcome Cok De, feeling nice it can hepled you.
Deleteand thanks for visited my website :)