Search code examples
jquerycompareselectedvalue

Several select box duplicate values compare


I want to compare select boxes selected option value, and if there are duplicate values in the select boxes I want to show alert:

alert("Duplicate value!");

This is my code:

<select class="examSelect">
    <option value="one">ba</opion>
    <option value="two">woo</opion>
    <option value="three">coo</opion>
    <option value="four">po</opion>
</select>

<select class="examSelect">
    <option value="one">ba</opion>
    <option value="two">woo</opion>
    <option value="three">coo</opion>
    <option value="four">po</opion>
</select>

<select class="examSelect">
    <option value="one">ba</opion>
    <option value="two">woo</opion>
    <option value="three">coo</opion>
    <option value="four">po</opion>
</select>

Solution

  • Here's an approach that uses object properties. It creates the property the first time it sees it, and if it sees that same value a second time, it breaks out and alerts.

    This could easily be modified to maintain a count of duplicates, e.g. "You entered 'woo' for 3 different selections!"

    It's also extensible for additional select boxes in your HTML with no modification since it's using jQuery each() to survey every matching dropdown.

    function checkit() {
        var checker = {};
        $(".examSelect").each(function() {
            var selection = $(this).val();
            if ( checker[selection] ) {
                //if the property is defined, then we've already encountered this value
                alert("Duplicate(s) detected!");
                return false;
            } else {
                //first time we've seen this value, so let's define a property for it
                checker[selection] = true;
            }
        });
        console.log(checker); //remove this in production
    }
    

    https://jsfiddle.net/y5y9uy5v/2/