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?

3
  • What values? They're all empty...You mean names? Commented Mar 7, 2012 at 3: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? Commented Mar 7, 2012 at 3:46
  • possible duplicate of prevent Duplicate values using Jquery Validation Commented Mar 7, 2012 at 3:48

1 Answer 1

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

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.