Remove spaces between links from html table if links removed

Viewed 77

I have below table in my jsp with links coming dynamically on page load using java arraylist

<%ArrayList<String> display  = ArrayList<String>)session.getAttribute("links");       %>
<table border="0" width="100%" style ="">
    <tr></tr>
    <td width="20%"></td>
    <table border="0" width ="50%" id="LinkDisplay">
        <div id="LinkDisplay">
            <%if(display!=null){
            for(int p=0;p<display.size();p++){%>
            <tr><td width="42%">&nbsp;</td><td><a href="javascript:removeLink('<%=display.get(p)%>')"><%=display.get(p)%></a><br></td><td>&nbsp;</td></tr>
            <% } }%>
        </div>
    </table>
    <td></td>
    <tr></tr>
</table>

When I click on link, it remove and hide the link calling removeLink javascript function

$('#LinkDisplay a').click(function() { 
    var $this = $(this);         
    $this.remove();
}

But when link remove, it leaves the spaces between links. How to remove that space, when link clicked. I tried to hide even tried to remove the empty td element (without link text) but it does not help.. Page with all the links look as below :-

enter image description here

after clicking on links it leaves the spaces as below :-

enter image description here

Also if there are more than 10 links I want to add scroll bars, can we do that on table. If table is not the right way to do all this, is there any other easy way?

2 Answers

You should remove the complete <TR>, .closest() can be used to traverse up to <TR> then remove it.

$('#LinkDisplay a').click(function () {
    var $this = $(this);
    $this.closest('tr').remove();
});

You are only removing the a element, you need to remove the whole tr:

$('#LinkDisplay a').click(function() { 
    var $this = $(this);         
    $this.parent().parent().remove();
}

Or even better $this.parent("#LinkDisplay tr").remove();.

Note:

  • You can't use the same id="LinkDisplay" for more than one element, you used it for table and div here.
  • Your HTML is invalid you can't have a div as immediate child of a table, it needs to be fixed.

And yes you can do this without a table, just use a div for each link, they will be displayed as block by default and use margin with your div instead of a td with &nbsp; as content, this way you can better manage the layout.

Related