asked on November 27, 2020

Hi, 

I have found a few threads on answers where with JS to identify if a row is duplicate, works great. I however have additional question. From the code below, how do I change it to auto delete a table row if it is a duplicate?

myTable can be replaced with actual table CSS and myField the actual CSS of the drop down field in the table. This displays a message when a duplicate is identified, but the table that I populate has hidden fields which won't be used on the initial step. At a different step, the hidden fields will be displayed and potentially there will be duplicate values, these values needs to be removed to make the table unique. There will only be 1 field, a drop-down field. This table will also be hidden from the user, but the unique value per row will be required to do some other functions.

 

 

 

 

$(document).ready(function(){
  // assign validator to initial rows
  assignValidator();
  
  // re-validate when a row is added or removed
  $('.services').on('click','.cf-table-add-row, .cf-table-delete',function(){
    assignValidator();
  });
});

function assignValidator(){
  // add unique validator
  $('.myTable .myField select').attr('data-parsley-uniqueselection','');

  // trigger validation on all rows when a row changes
  $('.myTable .myField select').off('change',validateSelection).on('change',validateSelection);
}

function validateSelection(){
  // revalidate the column if the value is not empty
  $('.myTable .myField').each(function(e){
      if($(this).val() != ''){
        $(this).parsley().validate();
      }
  });
}

window.Parsley.addValidator('uniqueselection', {
  validateString: function(value, requirement, field) {
    // return a list of all column values
    var valueList = field.$element.closest('.myTable').find('.myField select').map(
      function() {return $(this).val().trim(); }).get();

    // return the result of a filter for more than 1 match for the current field value
    return _.filter(valueList, function(v) { return v == value }).length == 1;
  },
  messages: {
    en: 'Duplicate selection.',
  }
});

Thanks

0 0