jack rose
jack rose

Reputation: 97

Avoid duplication using jquery

How to avoid duplication of data using jquery? My code is :

<button  id="gen">Generate</button>
<table id="report" border="1" style="visibility:hidden">
    <tr>
        <th>Sl.No.</th>
        <th>District Name</th>
    </tr>
</table>

js:

$("#gen").click(function(){
$("#report").css("visibility","visible");
for(var i=0; i<5; i++){
  var row='<tr><td>('+(i+1)+')</td></tr>'
  $("#report").append(row);
 }
});

Each time when i clicking the button, the same data were shown. How to avoid it? sqlfiddle: http://jsfiddle.net/etdx5o08/

Upvotes: 0

Views: 110

Answers (3)

Wesley Smith
Wesley Smith

Reputation: 19571

Do this:

$("#gen").click(function() {
       $("#report").parent().show();
       var rows='';
       for (var i = 0; i < 5; i++) {
         rows = rows+'<tr><td>(' + (i + 1) + ')</td><td></td></tr>'
       }
       $("#report").html(rows);
     });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="gen">Generate</button>
    <table border="1" style="display:none">
        <thead>
            <tr>
                <th>Sl.No.</th>
                <th>District Name</th>
            </tr>
        </thead>
        <tbody id="report"></tbody>
    </table>

Upvotes: 3

Prem
Prem

Reputation: 5974

To avoid duplicates, you can simply update js as below.

$("#gen").click(function(){
$("#report").css("visibility","visible");
$("#report").html('<tr><th>Sl.No.</th><th>District Name</th></tr>');
for(var i=0; i<5; i++)
    {
        var row='<tr><td>('+(i+1)+')</td></tr>'
        $("#report").append(row);
    }
});

Just adding the below line before loop starts.

$("#report").html('<tr><th>Sl.No.</th><th>District Name</th></tr>');

Here's jsFiddle.

Hope it helps :)

Upvotes: 0

ozil
ozil

Reputation: 7117

$("#gen").click(function(){
    $("#report").css("visibility","visible");
    var table = $("#report tbody tr");
    for(var i=0; i<5; i++){
        var row='<tr><td>('+(table.length+1+i)+')</td></tr>'
        $("#report").append(row);
    }
});  

Demo

Upvotes: 0

Related Questions