检查是否存在特定行

时间:2018-06-12 08:22:44

标签: javascript php jquery

我试图在桌面上动态创建行。当在自动完成时找到名称时,它将使用现有表创建行。但我的问题是我不想添加相同的产品。这里<tr></tr> id是唯一的。如何避免在表中添加相同的产品?

<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);           
      }           
    }
 })

2 个答案:

答案 0 :(得分:1)

要实现这一点,您可以通过选择它并检查生成的jQuery对象的id属性来检查DOM中是否已存在具有该length的元素,如下所示:

$('#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);
  }
});

答案 1 :(得分:0)

使用vanilla javascript

console.log(document.getElementById('' + ui.item.id) === null);
相关问题