2

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.

1
  • 3
    I must be being thick but...where does T come from? Commented Apr 1, 2014 at 23:15

5 Answers 5

2

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++;
})
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

Why the downvote? +1 to compensate, since it's actually what I suggested but with an array
@JuanMendes I was wondering the same thing, but it's gone now.
1

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

Comments

0

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.)

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.