html - How to select unique values from multiple dropdown lists using JavaScript? - Stack Overflow

I am building an online registration form. In the web form, there are six dropdown lists which is as fo

I am building an online registration form. In the web form, there are six dropdown lists which is as follows :

    <select name="hssub1" id="hssub1" onchange="checkUnique(this.id);">
        <option value="1">Bengali</option>
        <option value="2">English</option>
        <option value="3">Hindi</option>
        <option value="4">Physics</option>
        <option value="5">Chemistry</option>
        <option value="6">Mathematics</option>      
    </select>
    <select name="hssub2" id="hssub2" onchange="checkUnique(this.id);">
        <option value="1">Bengali</option>
        <option value="2">English</option>
        <option value="3">Hindi</option>
        <option value="4">Physics</option>
        <option value="5">Chemistry</option>
        <option value="6">Mathematics</option>  
    </select>
    <select name="hssub3" id="hssub3" onchange="checkUnique(this.id);">
        <option value="1">Bengali</option>
        <option value="2">English</option>
        <option value="3">Hindi</option>
        <option value="4">Physics</option>
        <option value="5">Chemistry</option>
        <option value="6">Mathematics</option>  
    </select>
    <select name="hssub4" id="hssub4" onchange="checkUnique(this.id);">
        <option value="1">Bengali</option>
        <option value="2">English</option>
        <option value="3">Hindi</option>
        <option value="4">Physics</option>
        <option value="5">Chemistry</option>
        <option value="6">Mathematics</option>  
    </select>
    <select name="hssub5" id="hssub5" onchange="checkUnique(this.id);">
        <option value="1">Bengali</option>
        <option value="2">English</option>
        <option value="3">Hindi</option>
        <option value="4">Physics</option>
        <option value="5">Chemistry</option>
        <option value="6">Mathematics</option>  
    </select>
    <select name="hssub6" id="hssub6" onchange="checkUnique(this.id);">
        <option value="1">Bengali</option>
        <option value="2">English</option>
        <option value="3">Hindi</option>
        <option value="4">Physics</option>
        <option value="5">Chemistry</option>
        <option value="6">Mathematics</option>  
    </select>

    <div id="notification"></div>

    <button type="button" name="submit" id="submit" onclick="return saveNext();">Save and Next</button>

Now I want the users to be able to select options which are mutually exclusive, i.e., the selection set from the six lists should contain unique values. To ensure this I devised the following JavaScript code:

function checkUnique(elementID) {
    var elt = document.getElementById(elementID);                       
    var hssubcode = document.getElementById(elementID).value;
    var elementIDsuffix = parseInt(elementID.substring(5)) - 1; 
    // to make it patible with array index

    var othercodes = [
        document.getElementById('hssub1').value,
        document.getElementById('hssub2').value,
        document.getElementById('hssub3').value,
        document.getElementById('hssub4').value,
        document.getElementById('hssub5').value,
        document.getElementById('hssub6').value
    ];
    for(var i=0; i<=5; i++){
        if(i != elementIDsuffix){
            if(othercodes[i] == hssubcode){
                document.getElementById("submit").setAttribute("disabled","disabled"); 
                // so that it stops form submission;
                document.getElementById("notification").innerHTML = elt.options[elt.selectedIndex].text + " Subject Already Choosen!";
                return false;
                break;
            } else {
                document.getElementById("notification").innerHTML = "";
                document.getElementById("submit").removeAttribute("disabled");    
                // so that it allows form submission again;
            }
        }    
    }
}

The above script fails when the user first selects say Bengali, then again Bengali, then again Bengali and finally changes the second choice. I can understand the problem in the code, but being a novice programmer, I am unable to think how to build up the required logic. Please help.

I am building an online registration form. In the web form, there are six dropdown lists which is as follows :

    <select name="hssub1" id="hssub1" onchange="checkUnique(this.id);">
        <option value="1">Bengali</option>
        <option value="2">English</option>
        <option value="3">Hindi</option>
        <option value="4">Physics</option>
        <option value="5">Chemistry</option>
        <option value="6">Mathematics</option>      
    </select>
    <select name="hssub2" id="hssub2" onchange="checkUnique(this.id);">
        <option value="1">Bengali</option>
        <option value="2">English</option>
        <option value="3">Hindi</option>
        <option value="4">Physics</option>
        <option value="5">Chemistry</option>
        <option value="6">Mathematics</option>  
    </select>
    <select name="hssub3" id="hssub3" onchange="checkUnique(this.id);">
        <option value="1">Bengali</option>
        <option value="2">English</option>
        <option value="3">Hindi</option>
        <option value="4">Physics</option>
        <option value="5">Chemistry</option>
        <option value="6">Mathematics</option>  
    </select>
    <select name="hssub4" id="hssub4" onchange="checkUnique(this.id);">
        <option value="1">Bengali</option>
        <option value="2">English</option>
        <option value="3">Hindi</option>
        <option value="4">Physics</option>
        <option value="5">Chemistry</option>
        <option value="6">Mathematics</option>  
    </select>
    <select name="hssub5" id="hssub5" onchange="checkUnique(this.id);">
        <option value="1">Bengali</option>
        <option value="2">English</option>
        <option value="3">Hindi</option>
        <option value="4">Physics</option>
        <option value="5">Chemistry</option>
        <option value="6">Mathematics</option>  
    </select>
    <select name="hssub6" id="hssub6" onchange="checkUnique(this.id);">
        <option value="1">Bengali</option>
        <option value="2">English</option>
        <option value="3">Hindi</option>
        <option value="4">Physics</option>
        <option value="5">Chemistry</option>
        <option value="6">Mathematics</option>  
    </select>

    <div id="notification"></div>

    <button type="button" name="submit" id="submit" onclick="return saveNext();">Save and Next</button>

Now I want the users to be able to select options which are mutually exclusive, i.e., the selection set from the six lists should contain unique values. To ensure this I devised the following JavaScript code:

function checkUnique(elementID) {
    var elt = document.getElementById(elementID);                       
    var hssubcode = document.getElementById(elementID).value;
    var elementIDsuffix = parseInt(elementID.substring(5)) - 1; 
    // to make it patible with array index

    var othercodes = [
        document.getElementById('hssub1').value,
        document.getElementById('hssub2').value,
        document.getElementById('hssub3').value,
        document.getElementById('hssub4').value,
        document.getElementById('hssub5').value,
        document.getElementById('hssub6').value
    ];
    for(var i=0; i<=5; i++){
        if(i != elementIDsuffix){
            if(othercodes[i] == hssubcode){
                document.getElementById("submit").setAttribute("disabled","disabled"); 
                // so that it stops form submission;
                document.getElementById("notification").innerHTML = elt.options[elt.selectedIndex].text + " Subject Already Choosen!";
                return false;
                break;
            } else {
                document.getElementById("notification").innerHTML = "";
                document.getElementById("submit").removeAttribute("disabled");    
                // so that it allows form submission again;
            }
        }    
    }
}

The above script fails when the user first selects say Bengali, then again Bengali, then again Bengali and finally changes the second choice. I can understand the problem in the code, but being a novice programmer, I am unable to think how to build up the required logic. Please help.

Share Improve this question edited May 10, 2015 at 13:21 jensblond 455 bronze badges asked May 10, 2015 at 12:27 samlancersamlancer 1332 silver badges13 bronze badges 1
  • With jQuery there's selectunique and uniqselect. Of the two selectunique is more robust. – DBagBaggerWithSwagger Commented Sep 29, 2015 at 0:15
Add a ment  | 

5 Answers 5

Reset to default 1

You could use an empty object as a dictionary and count how many occurrences there are for each value. If any value occurrs over 2 times, disable the submit:

function checkUnique(elementID) {
    var elt = document.getElementById(elementID);                       
    var valCounter = {};

    var othercodes = [
        document.getElementById('hssub1').value,
        document.getElementById('hssub2').value,
        document.getElementById('hssub3').value,
        document.getElementById('hssub4').value,
        document.getElementById('hssub5').value,
        document.getElementById('hssub6').value
    ];
    for(var i=0; i<=5; i++){
        var c = valCounter[othercodes[i]] = (valCounter[othercodes[i]] || 0) + 1;
        if(c > 1){
            document.getElementById("submit").setAttribute("disabled","disabled"); 
            // so that it stops form submission;
            document.getElementById("notification").innerHTML = elt.options[elt.selectedIndex].text + " Subject Already Choosen!";
            return false;
        }
    }
    document.getElementById("notification").innerHTML = "";
    document.getElementById("submit").removeAttribute("disabled");    
    // so that it allows form submission again;
}

First, I would suggest using a default option like "Select subject" whose value is "null" or 0 - something that can be easily discarded. This way there are no default selected values. Second, I would highly remend not putting the event handlers in your markup. It's a real mess to maintain that.

<select name="hssub1" id="hssub1">
    <option value=null>Select</option> //added default option
    <option value="1">Bengali</option>
    <option value="2">English</option>
    <option value="3">Hindi</option>
    <option value="4">Physics</option>
    <option value="5">Chemistry</option>
    <option value="6">Mathematics</option>      
</select>
<select name="hssub2" id="hssub2">
    <option value=null>Select</option>
    <option value="1">Bengali</option>
    <option value="2">English</option>
    <option value="3">Hindi</option>
    <option value="4">Physics</option>
    <option value="5">Chemistry</option>
    <option value="6">Mathematics</option>  
</select>
<select name="hssub3" id="hssub3">
    <option value=null>Select</option>
    <option value="1">Bengali</option>
    <option value="2">English</option>
    <option value="3">Hindi</option>
    <option value="4">Physics</option>
    <option value="5">Chemistry</option>
    <option value="6">Mathematics</option>  
</select>
<select name="hssub4" id="hssub4">
    <option value=null>Select</option>
    <option value="1">Bengali</option>
    <option value="2">English</option>
    <option value="3">Hindi</option>
    <option value="4">Physics</option>
    <option value="5">Chemistry</option>
    <option value="6">Mathematics</option>  
</select>
<select name="hssub5" id="hssub5">
    <option value=null>Select</option>
    <option value="1">Bengali</option>
    <option value="2">English</option>
    <option value="3">Hindi</option>
    <option value="4">Physics</option>
    <option value="5">Chemistry</option>
    <option value="6">Mathematics</option>  
</select>
<select name="hssub6" id="hssub6">
    <option value=null>Select</option>
    <option value="1">Bengali</option>
    <option value="2">English</option>
    <option value="3">Hindi</option>
    <option value="4">Physics</option>
    <option value="5">Chemistry</option>
    <option value="6">Mathematics</option>  
</select>

<div id="notification"></div>

<button type="button" name="submit" id="submit">Save and Next</button>

Here's the Javascript -fairly straightforward, but you can ask in case of any questions:

var selects = document.querySelectorAll('select'),
    notify = document.getElementById('notification');

function getOthers(current){
    var values = [];
    for(var i=0;i<selects.length;i++){
        if(selects[i].value!='null' && selects[i]!=current)
            values.push(selects[i].value);
    }
    return values;
}

function checkUnique(){
    if(this.value && getOthers(this).indexOf(this.value)>-1){
        notify.innerText = 'You already selected that';
        this.value = null;
    }
}

for(var i=0;i<selects.length;i++)
    selects[i].onchange = checkUnique;

document.getElementById('submit').onclick = function(){
    var values = getOthers(); // will return all selected values this time
    if(values.length < 6){
        notify.innerText = 'select all six';
        return false;
    }
    notify.innerText = '';
    return true;
}

A fiddle: http://jsfiddle/p699m9x7/

First add new option to lists with an value you can easily recognize like this:

<select name="hssub1" id="hssub1" onchange="checkUnique(this.id);">
    <option value="null">Select</option>
    <option value="1">Bengali</option>

then add if condition before the conditions you have now and then the loop will be like this:

for(var i=0; i<=5; i++){
    if(i != elementIDsuffix){
        if(othercodes[i] === "null"){ //check whether anything is null
            document.getElementById("notification").innerHTML = "Select in all lists to continue"; // if null print this
        }else if(othercodes[i] == hssubcode){
            document.getElementById("submit").setAttribute("disabled","disabled");
            document.getElementById("notification").innerHTML = elt.options[elt.selectedIndex].text + " Subject Already Choosen!";
            return false;
            break;
        } else{ 
            document.getElementById("notification").innerHTML = "";
            document.getElementById("submit").removeAttribute("disabled");
        }
    }
}

but with this at first time you enter the page the button will not disable. So for that call this function on body onload event;

<body onload="checkUnique('hssub1');">

I think this will help you to continue with minimal changes to your existing code

There's this JavaScript snippet on github. Just a 1.4 kB js file. Just include jquery before including the script and you should be good to go.

https://github./akhilnaik/unique.js

You need to give a class for all the < select > tags you want to have unique values
Here I'm using class='abc' as example.

<select class='abc' name="hssub1" id="hssub1" onchange="checkUnique(this.id);">
    <option value="null">Select One</option>
    <option value="1">Bengali</option>
    <option value="2">English</option>
    <option value="3">Hindi</option>
    <option value="4">Physics</option>
    <option value="5">Chemistry</option>
    <option value="6">Mathematics</option>      
</select>
<select class='abc' name="hssub2" id="hssub2" onchange="checkUnique(this.id);">
    <option value="null">Select One</option>
    <option value="1">Bengali</option>
    <option value="2">English</option>
    <option value="3">Hindi</option>
    <option value="4">Physics</option>
    <option value="5">Chemistry</option>
    <option value="6">Mathematics</option>  
</select>
and so on .....

And call the constructor of Unique on window.onload like this

var k = new Unique('.abc','null');//u need to have a default null value

And thats it everything is taken care of.
The selected values will automatically be disabled.

Dont forget to include JQuery before including unique.js
Hope this helps.

I don't know if this fits your needs, but if you want to get a warning, if any value is already chosen, you could do it like that:

function checkUnique(elementID) {
  var values = [];
  var elements = document.getElementsByTagName('select');
  for (var i=0, l=elements.length; i < l; i++) {
    if (document.getElementById(elementID).value === elements[i].value && document.getElementById(elementID) != elements[i]) {
      console.log('not unique');
    }
  }
}

Instead of console.log('not unique') you could do your warnings.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744786864a4593678.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信