How to check if ID already exists - JS

When the user selects an item, I save the iditem to hidden inputin the panel. Now, when the user selects the same item, I want to check if idthe panel exists , and if that happens, I will change the quantity value from 1 to 2.

How can i achieve this?

PS: When using the code below, when the user selects an existing item in the panel, he adds the item again, and I have duplicates.

function findID(sol)
{
    var products = JSON.parse(sol.dataset.sol);

    if(sol.checked == true)  {
        $('.panel').append(
            '<div class="container" style=" font-size:14px; "> '+
            '<input type="hidden"  value='+products.id+' data-id="'+products.id+'"   name="food_id[]" />'+
            '<table style="width:100%;" class="table" id="tables">'+

            '<tbody id="item_list">'+
            '<tr>'+
            '<td  class="name" >'+products.name+'</td>'+
            '<td><input size="50" type="text"  value="1" class="form-control quantity" id="qty" placeholder=" qty " name="quantity[]"  required/></td>'+
            '</tr>'+
            '</tbody>'+
            '</table>'+
            '</div>'

        )
    }
}
+4
source share
2 answers

You just need to scan the DOM for already added elements, and if it exists, find the element .quantityand increase the value. Other wise add it as you already do

function findID(sol) {
  var products = JSON.parse(sol.dataset.sol),
    existing;

  if (sol.checked == true) {
    existing = $('.panel input[data-id="' + ad.id + '"]');

    if (existing.length) {
      // already added, just increase the count
      existing.closest('.container').find('.quantity').val(function(i, value) {
        return parseInt(value, 10) + 1;
      })
    } else {
      // not yet added. Add it now
      $('.panel').append(
        '<div class="container" style=" font-size:14px; "> ' +
        '<input type="hidden"  value=' + ad.id + ' data-id="' + ad.id + '"   name="food_id[]" />' +
        '<table style="width:100%;" class="table">' +

        '<tbody id="item_list">' +
        '<tr>' +
        '<td  class="name" >' + ad.name + '</td>' +
        '<td><input size="50" type="text"  value="1" class="form-control quantity" placeholder=" qty " name="quantity[]"  required/></td>' +
        '</tr>' +
        '</tbody>' +
        '</table>' +
        '</div>'

      )
    }


  }
Run codeHide result

id , .

+2

.

var selectedIds = $('.panel').data('selectedIds') || [];

if (selectedIds.indexOf(newSelectedId) > -1) {
    //id already selected
    //do whatever logic
} else {
    //id not already selected
    selectedIds.push(newSelectedId);
    $('.panel').data('selectedIds', selectedIds);
    //do your other logic
}
0

Source: https://habr.com/ru/post/1691049/


All Articles