Reputation: 3638
The below fiddle is from another question. It contains the output of a dynamic addition and deletion of html table rows using javascript. The code in the fiddle gave me what i want. But i have one problem with the code. While deleting the rows one by one, the first row is also getting deleted. How can i hide the delete button only in the first row ?
<div id="POItablediv">
<input type="button" id="addPOIbutton" value="Add POIs"/><br/><br/>
<table id="POITable" border="1">
<tr>
<td>POI</td>
<td>Latitude</td>
<td>Longitude</td>
<td>Delete?</td>
<td>Add Rows?</td>
</tr>
<tr>
<td>1</td>
<td><input size=25 type="text" id="latbox"/></td>
<td><input size=25 type="text" id="lngbox" readonly=true/></td>
<td><input type="button" id="delPOIbutton" value="Delete" onclick="deleteRow(this)"/></td>
<td><input type="button" id="addmorePOIbutton" value="Add More POIs" onclick="insRow()"/></td>
</tr>
</table>
function deleteRow(row)
{
var i=row.parentNode.parentNode.rowIndex;
document.getElementById('POITable').deleteRow(i);
}
function insRow()
{
console.log( 'hi');
var x=document.getElementById('POITable');
var new_row = x.rows[1].cloneNode(true);
var len = x.rows.length;
new_row.cells[0].innerHTML = len;
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 );
}
Above is the code in the fiddle. Hope this helps if you can't load fiddle. It happens sometimes.
Upvotes: 3
Views: 1667
Reputation: 2985
just add the following line in the script
new_row.cells[3].getElementsByTagName('input')[0].removeAttribute('style');
Plus a little modification in the HTML (add disabled to true in the first delete button)
<td><input type="button" id="delPOIbutton" value="Delete" onclick="deleteRow(this)" style="display:none"/></td>
Check fiddle: http://jsfiddle.net/7AeDQ/25/
Upvotes: 1
Reputation: 3460
This looks elegant.
Hide the first:
$("table tr:eq(1) td:eq(3) input").css("display","none");
Then show the newly created tr:
var noRows = $("#POITable tr").length-1;
$("table tr:eq("+noRows+") td:eq(3) input").css("display","block");
Fiddle: http://jsfiddle.net/Lh8KL/
Upvotes: 2
Reputation: 816364
Just add this statement:
x.rows[1].cells[3].children[0].style.display = x.rows.length > 2 ? '' : 'none';
This gets a reference to the input
element in the first row in the third cell and hides it if there is only one row.
Updated fiddle: http://jsfiddle.net/7AeDQ/23/
Upvotes: 2