You are viewing limited content. For full access, please sign in.

Question

Question

Unique values in a collection

asked on August 3, 2016 Show version history

Hi,

I am trying to implement a collection which has only one field with unique values. If it is repeated field turn red.

So far it works well when adding a new field

 $('.cf-collection-block').on('blur','input',function(){

    var current_value = $(this).val();
    var repeated= false;
    $('.cf-collection-block ul').each(function(index){
      
      
      var size= $('.cf-collection-block ul').size();
      
      if ( (current_value == $(this).find('#q14 input').val()) && (size > 1) && ( index!= size-1 ))
      {
        repeated = true;
      }
      else
      {
        
      }
    }); // for each
    
    if (repeated == true)
    {
      repeated = false;
      current_index=0;
      this.setAttribute('style', 'background-color: rgb(255,224,224)  !important');
    }
  });

Size>1 makes sure that first value doesn't compare itself and index = size -1 is for last value which was just added.

Problem is when i click /edit any value that is unique but was added earlier (already there) it turns red even though it is unique.

I believe inside for each loop it compares itself which is a problem. 

Any solution?

Thanks in advance.

Junaid Inam

0 0

Answer

SELECTED ANSWER
replied on August 3, 2016

Probably best to make use of jQuery and JavaScript Arrays to make this a little simpler (map, index, indexOf, splice, join, etc...). Here's what I would do (should work well assuming your list doesn't get too long... this code checks each row against all other rows whenever any value changes (O(n^2)).

$(document).ready(function(){
  $('.cf-collection-block').on('blur','div.form-q',function(){
    $('.cf-collection-block div.form-q').each(function(){
      var curIndex = $(this).index();
      var vals = $('.cf-collection-block ul input').map(function(){return($(this).val());}).get();
      vals.splice(curIndex,1);
      if(vals.indexOf($(this).find('ul input').val())>-1){
        $(this).find('ul').css('background-color','rgb(255,224,224)!important');
      }else{
        $(this).find('ul').css('background-color','transparent');
      }
    });
  });
});

 

1 0
replied on August 4, 2016

Thanks Scott.

0 0

Replies

You are not allowed to reply in this post.
You are not allowed to follow up in this post.

Sign in to reply to this post.