Question

I have a form with 3 input file fields. I want to make sure that they do not upload the same document twice. Right now my code is as follows:

$(':input.File').each(function() {
    if ($(this).val() == T) {
        $this.after('<br/><span class="error">Duplicate</span>');
    }
})

The code works but my issue is that it always throws the error because it is comparing against itself. It identifies all file fields when I want it to compare all file fields but itself.

Is there a way to exclude the field being compared against? Essentially I want to check all the file field value except for the $(this) field.

Was it helpful?

Solution

If you know there is always going to be at least one duplicate, why not just allow one duplicate?

i = 0;
$(':input.File').each(function() {
    if ($(this).val() == T && i != 0) {
        $this.after('<br/><span class="error">Duplicate</span>');
    }

    i++;
})

OTHER TIPS

Make an empty array, then go through each field and check if that field is in the array if not add it.

var arr = [];

$(':input.File').each(function(){
    if(arr.indexOf($(this).val()) > -1){
        $(this).after("<br/><span class='error'>Duplicate</span> ");
    }else{
        arr.push($(this).val());
    }
})

You can use a map to keep track of what values exist

(function(){
  var exists = {};
  $(':input.File').each(function() {
    if(exists[$(this).val()]){
      $this.after("<br/><span class='error'>Duplicate</span> ");
    } else {
      exists[$(this).val()] = true;
    }
  });
})()

I have a feeling this is what you are looking for:

jQuery: exclude $(this) from selector

In order to give you a more specific answer, I'd need a bit more code context. (IE. what is T, how it that code reached, etc.)

For a checkup after each user action:

$('input[type=file]').change(function(){
     $('input[type=file][value="'+$(this).val()+'"]').not(this).after("<br/><span class='error'>Duplicate</span> ");
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top