简体   繁体   English

在 select2 jquery 或 javascript 中的下一个 select 框中隐藏所选选项

[英]Hide selected option in next select box in select2 jquery or javascript

I stuck in this issue which is when a user selects an option from one select box the option should be hidden for the other select boxes.我陷入了这个问题,即当用户从一个 select 框中选择一个选项时,该选项应该为其他 select 框隐藏。 When a selected option changes the previously selected option should become available again to the other select boxes. When a selected option changes the previously selected option should become available again to the other select boxes.

The problem with my current code:我当前代码的问题:

My code is working when the select box is normal option, if I change to select2 it will not function.当 select 框是正常选项时,我的代码正在工作,如果我更改为 select2 它不会 function。 Anyone know how to do it if the select box is select2:(?如果 select 框是 select2:(?

Code: http://jsfiddle.net/t8170aqg/1/

There are few issues in your code您的代码中几乎没有问题

  1. You are using val in option which is not correct your should use value您在选项中使用val不正确,您应该使用value
  2. Also you not matching with val() of the selected option in the previous select you are mat aching the text which will be always different.此外,您与之前 select 中所选选项的 val() 不匹配,您正在匹配始终不同的文本。

Edit: You have to use .each to set attr disabled for other options.编辑:您必须使用.each为其他选项设置禁用attr

Working Fiddle Demo: http://jsfiddle.net/usmanmunir/bqzt1rf9/工作小提琴演示: http://jsfiddle.net/usmanmunir/bqzt1rf9/

Run snippet below to see it working.运行下面的代码片段以查看它的工作原理。

Using disabled attr on option在选项上使用禁用的属性

 $(".s").select2() $('.s').change(function() { let value = $(this).val() $(this).siblings('.s').children('option').attr('disabled', false) $('.s').each(function() { $(this).siblings('.s').children('option[value=' + $(this).val() + ']').attr('disabled', 'disabled') }) })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/css/select2.min.css" rel="stylesheet" /> <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/js/select2.min.js"></script> <select class="datas_0 s"> <option selected disabled>Choose</option> <option value="1">lim</option> <option value="2">tan</option> <option value="3">alax</option> <option value="4">king</option> </select> <br> <br> <select class="datas_1 s"> <option selected disabled>Choose</option> <option value="1">lim</option> <option value="2">tan</option> <option value="3">alex</option> <option value="4">king</option> </select> <br> <br> <select class="datas_2 s"> <option selected disabled>Choose</option> <option value="1">lim</option> <option value="2">tan</option> <option value="3">alex</option> <option value="4">king</option> </select>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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