Several select box duplicate values compare

隐身守侯 提交于 2020-01-03 03:47:06

问题


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>

回答1:


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/




回答2:


you can use something like this to compare all of three select ..the next code will check if all of them has a same value alert yes .. make if statements you need

$(document).ready(function(){
    $('.examSelect').on('change',function(){
        var examSelect0 = $('.examSelect').eq(0).val();
        var examSelect1 = $('.examSelect').eq(1).val();
        var examSelect2 = $('.examSelect').eq(2).val();
        if(examSelect0 == examSelect1 && examSelect1 == examSelect2){
            alert('yes');
        }
    });
});

DEMO

you can use this if statement if value duplicated on 2 of them

if(examSelect0 == examSelect1 || examSelect1 == examSelect2 || examSelect0 == examSelect2){
     alert("Duplicate value!");
 }


来源:https://stackoverflow.com/questions/33928605/several-select-box-duplicate-values-compare

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!