简体   繁体   中英

How can I compare two select menus with JavaScript?

I have two select menus and I want to compare them. If I choose the first select options, I want to disable option which has same name in second select menu. How can I do this with only using JavaScript? And also I want to write to p element all selected options values from both side.

 <form> <select multiple class="form-control" id="f144" onchange=""> <option>REAR CASE</option> <option>CASE ASSEMBLY</option> <option>POLE CLAMP ASS</option> <option>POLE CLAMP KNOB</option> <option>COVER PERIPHERAL</option> <option>RETAINER CORD</option> </select> </form> <form> <select multiple class="form-control" for="fvisual" onchange=""> <option>CASE ASSEMBLY</option> <option>FRONT CASE</option> <option>REAR CASE</option> <option>ASM DOOR</option> <option>SHIELD</option> <option>KEYPAD</option> <option>DISPLAY</option> <option>HANDLE DOOR</option> <option>RETAINER CORD</option> <option>POLE CLAMP ASS</option> <option>POLE CLAMP KNOB</option> <option>COVER PERIPHERAL</option> </select> </form> <p id="p1"></p>

Here's my answer. I've compared two selection menus and I've disabled the options I want. But there's still something I want to do. I want to do, which option is selected deselection when I click a second time. But the solution in my mind didn't work.

 var a = document.f1.s1; var b = document.f2.s1; var array = [false, false, false, false]; function disable() { for (i = 0; i < a.length; i++) { if (a[i].selected && array[i] == false) { for (j = 0; j < b.length; j++) { if (a[i].value == b[j].value) { b[j].setAttribute("disabled", true); } } array[i] = true; } else if (a[i].selected && array[i] == true) { a[i].selected = false; array[i] = false; } } }
 <form name="f1"> <select name="s1" multiple onchange="disable()"> <option>ABCDE</option> <option>BCDEF</option> <option>CDEFG</option> <option>DEFGH</option> </select> </form> <form name="f2"> <select name="s1" multiple> <option>ABCDE</option> <option>BCDEF</option> <option>CDEFG</option> <option>DEFGH</option> </select> </form>

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