Prevent Duplicate Append data in JavaScript and Html

Issue

I have one HTML table and I don’t want the value of second column to repeat in the grid.
Here is my JavaScript:

var $addedProductCodes = [];

function getProductData(value){

        $td_productCode=$("#sales-product-code").val();
        var index = $.inArray($td_productCode, $addedProductCodes);
        if (index >= 0) {
                alert("You already added this Product");
            } else {
                $('#test').append("<tr><td>"+ value +"</td></tr>");
                $addedProductCodes.push($td_productCode);
            }
        }

and Html

    <tbody  id="test">
  <tr>
    <td><input type="text" id="sales-product-code" name="cm_code[]" value="" class="sales-product-code"/> </td>
  </tr>
</tbody>

Please help me out. Help is highly appreciated.

Solution

The call to

$('#test').append("<tr><td>"+ value +"</td></tr>") 

should be replaced with

$('#test tr:last').after("<tr><td>" + value + "</td></tr>").

I created a JSFiddle example.

Answered By – NIck

Answer Checked By – David Goodson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.