Hola
Hola

Reputation: 2233

check if specific row exist

I was trying to create row dynamically on table. When a name found on autocomplete it will create row with the existing table. But my problem is i don't want to add same product in row. here <tr></tr> id is unique. How to avoid adding same product in the table?

<table class="table m-table ">
   <thead>
     <tr> 
       <th></th>                   
       <th>Product Name</th>
       <th>Unit Price</th>
       <th>Quantity</th>                   
       <th>Total </th>
     </tr>
    </thead>
      <tbody>
     </tbody>
 </table>   
 $('#productSearch').autocomplete({
    source: '{!! asset('productSearch') !!}',
    select:function(suggestion, ui) {
      {
        var markup = "<tr id="+ui.item.id+"><td><i class='flaticon-delete-1 delete-row' onclick='deleteRow(this)'></i></td><td>"+ui.item.value+"</td><td>"+ui.item.unit_price+"</td><td><input type='text' class='quantity' value='1'></td><td class='total'>"+ui.item.unit_price+"</td></tr>"; 
        $("table tbody").append(markup);           
      }           
    }
 })

Upvotes: 1

Views: 1406

Answers (2)

nice_dev
nice_dev

Reputation: 17805

Using vanilla javascript

console.log(document.getElementById('' + ui.item.id) === null);

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

To achieve this you can check if an element with that id already exists in the DOM by selecting it and checking the length property of the resulting jQuery object, like this:

$('#productSearch').autocomplete({
  source: '{!! asset('productSearch') !!}',
  select: function(suggestion, ui) {
    if ($('#' + ui.item.id).length !== 0) 
      return;

    var markup = '<tr id="' + ui.item.id + '"><td><i class="flaticon-delete-1 delete-row" onclick="deleteRow(this)"></i></td><td>' + ui.item.value + '</td><td>' + ui.item.unit_price + '</td><td><input type="text" class="quantity" value="1"></td><td class="total">' + ui.item.unit_price + '</td></tr>';
    $('table tbody').append(markup);
  }
});

Upvotes: 1

Related Questions