简体   繁体   中英

how to Disable multiple selected dropdown values in javascript

I have one add button if i click it then it generates one new line having one dropdown(Multiple selection allowed) ,now if i ve selected some value in the dropdown next time if i press add button again it will generate the same dropdown in a new line but i want user should not able to select the previously selected items in the newly created dropdown.ie each and every dropdown should have unique values selected.

<select multiple="true" id="mySelect[0]">
  <option value="1" >Apple</option>
  <option value="2">Pear</option>
  <option value="3">Banana</option>
  <option value="4">Orange</option>
</select>
<select multiple="true" id="mySelect[1]">
  <option value="1" >Apple</option>
  <option value="2">Pear</option>
  <option value="3">Banana</option>
  <option value="4">Orange</option>
</select>
<select multiple="true" id="mySelect[2]">
  <option value="1" >Apple</option>
  <option value="2">Pear</option>
  <option value="3">Banana</option>
  <option value="4">Orange</option>
</select>

if apple,pear is seleted in the 1st drop down then in next two dropdown apple option should be disabled and colored with red.

This should give you a good idea of how to start:

//cancels given event
function cancelEvent(ev) {
    ev.preventDefault();
    ev.returnValue = false; 
    ev.cancelBubble = true;
    return false;
}

function checkSelection(e) {
var oSel = e.target
var oPrvSel;

    for(var i=0; i<e.target.index; i++) {
        oPrvSel = document.getElementById("mySelect[" + i + "]");
        for(var j=0; j<oPrvSel.options.length; j++) {
            if (oPrvSel.options[j].text == e.target.options[e.target.selectedIndex].text) return cancelEvent(e);
        }
    }

}



//at instanciation of new elements:
var oSel = document.getElementById("mySelect[" + i + "]");
oSel.index = i;
oSel.addEventListener("keydown", checkSelection, false);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM