0

I have a dynamically generated form with multiple text input fields:

<input class="w200" type="text" value="" name="field[7018]">
<input class="w200" type="text" value="" name="field[7019]">
<input class="w200" type="text" value="" name="field[7020]">
...
<input class="w200" type="text" value="" name="field[7055]">

Using jQuery, how can I detect duplicate values on input?

There's a post on SO that proposes the following solution:

$("#check").click(function() {
    $.post("checkname.php", 
           { name : $("#textboxname").val() },
           function(data) {
             //data will contain the output from the file `checkname.php`
             if(data=="ok") { //imagine the case it output ok if not duplicate is found
                alert('ok');
             else { 
                alert('duplicate name exists');
             }
    );
});

It works if a use enters one value at a time. But what if the user gets opens a form with prepopulated values, to edit them. How would I check for duplicates then?

Community
  • 1
  • 1
santa
  • 12,234
  • 49
  • 155
  • 255
  • What values? They're all empty...You mean `names`? – elclanrs Mar 07 '12 at 03:44
  • @elclanrs: I think the OP wants to verify each input's value is unique when the user submits the form. santa: Is each field required, or if not: are two empty values considered duplicate? – Wesley Murch Mar 07 '12 at 03:46
  • possible duplicate of [prevent Duplicate values using Jquery Validation](http://stackoverflow.com/questions/2955536/prevent-duplicate-values-using-jquery-validation) – j08691 Mar 07 '12 at 03:48

1 Answers1

0

If you are asking for how to check the duplicate values of existing input-elements on a page, do like this :

$("input[type='text']").change( function() {
    // check input ($(this).val()) for validity here
    var valueOfChangedInput = $(this).val();
    var timeRepeated = 0;
    $("input[type='text']").each(function () {
        //Inside each() check the 'valueOfChangedInput' with all other existing input
        if ($(this).val() == valueOfChangedInput ) {
            timeRepeated++; //this will be executed at least 1 time because of the input, which is changed just now
        }
    });

    if(timeRepeated > 1) {
        alert("Duplicate value found !");
    }
    else {
        alert("No Duplicates !");
    }
});
tusar
  • 3,364
  • 6
  • 37
  • 60