Find duplicates values in a set of textboxes using jQuery

Well sometime back, I faced this unique problem. It took me sometime to solve it, so I thought of documenting it as my learning so that it is useful for others and might help me one when I need to do it again.

Problem

Okay, the following is the requirement. You have a web page with a set of text boxes. The number of text-boxes might vary based on some backend logic. You need to make sure the user doesn’t enter duplicate values in these set of textboxes. He can leave them blank, but cannot enter duplicate values.

Solution

The following is my solution.

function findDuplicates() {
    var isDuplicate = false;
    jQuery("input[name^='access_keys']").each(function (i,el1) {
        var current_val = jQuery(el1).val();
        if (current_val != "") {
            jQuery("input[name^='access_keys']").each(function (i,el2) {
                if (jQuery(el2).val() == current_val && jQuery(el1).attr("name") != jQuery(el2).attr("name")) {
                    isDuplicate = true;
                    jQuery(el2).css("background-color", "yellow");
                    jQuery(el1).css("background-color", "yellow");
                    return;
                }
            });
        }
    });

    if (isDuplicate) {
        alert ("Duplicate values found.");
        return false;
    } else {
        return true;
    }
}

I basically loop through all the text boxes and compare the values with all the other textboxes, in nested loops. Basically it is like bubble sort. I know this is bad, but was not able to think of any efficient way of doing it. Do you guys can think of a better way?

Related posts

Tags: , ,

3 Comments so far

Follow up comments through RSS Feed | Post a comment

  • rsaiprasad says:

    Create an object with “values” of the input boxes as keys and data being an array holding the ‘textboxes’ with that value.
    {“abc”:[inputbox1, inputbox2],”xyz”:[inputbox2, inputbox3]}
    This can be done in one iteration.

    Then do another iteration on the object and highlight all the textboxes in the values whose length is > 2.

    • rsaiprasad says:

      oops typos.

      The object would look like
      {“abc”:[inputbox1, inputbox2],”xyz”:[inputbox3, inputbox4,inputbox5]..}

      you need to look for length >=2.

  • Amar says:

    could you provide an online demo

1 Tweetbacks so far

Leave a Reply to rsaiprasad Cancel reply

Your email address will not be published. Required fields are marked *