使用jQuery使用optgroup选项名称显示下拉值

时间:2019-06-02 09:02:43

标签: javascript jquery

我有下拉分组列表(Optgroup)。需要根据下拉菜单下方第一个optgroup中的选定值显示第二个optgroup中的值。

const needle = '[DO NOT ALLOW SELECT FOR THIS]';
// using jQuery:
$('select option').prop('disabled', function() {
  return this.text.includes(needle);
});

$("#caption_collection").change(function() {
  $('#selected').html(' ');
  $("#caption_collection option:selected").each(function() {
    var $this = $(this);
    if ($this.length) {
      var selText = $this.text();
      console.log(selText);
      $('#selected').append(selText + ', ');
      //$('#selected').text('Only Captions allowed are:').append(selText + ', ');
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select multiple="multiple" size=20 id="caption_collection">

  <optgroup label="MAKE A CHOICE">
    <option>ALLOW SELECT HERE</option>
    <option>DO NOT ALLOW SELECT FOR THIS</option>
    <option>SHOW ALL LISTED CAPTIONS</option>
  </optgroup>
  <optgroup label="ELSE SELECT ONE OR MULTIPLE">
    <option>ALWCaption-A100104 [ALLOW SELECT HERE]</option>
    <option>ZSDCaption-Z100104 [ALLOW SELECT HERE]</option>
    <option>XCDCaption-S100104 [ALLOW SELECT HERE]</option>
    <option>DCVCaption-Q100104 [ALLOW SELECT HERE]</option>
    <option>ERTCaption-D100104 [ALLOW SELECT HERE]</option>
    <option>BNMCaption-XX223366 [DO NOT ALLOW SELECT FOR THIS]</option>
    <option>XWECaption-XX243356 [DO NOT ALLOW SELECT FOR THIS]</option>
    <option>QWECaption-XX323356 [DO NOT ALLOW SELECT FOR THIS]</option>
    <option>DFGCaption-XX228866 [DO NOT ALLOW SELECT FOR THIS]</option>
    <option>TYUCaption-XX220066 [DO NOT ALLOW SELECT FOR THIS]</option>
    <option>POICaption-XX423366 [DO NOT ALLOW SELECT FOR THIS]</option>
    <option>GHJCaption-D100104 [ALLOW SELECT HERE]</option>
    <option>LKICaption-D100104 [ALLOW SELECT HERE]</option>
    <option>UYTCaption-XX423366 [DO NOT ALLOW SELECT FOR THIS]</option>
  </optgroup>

</select>
<br><br>
<div>
  <textarea id="selected" rows="4" cols="56" readonly></textarea>
</div>

第一个选择组“进行选择”下有3个选项

ALLOW SELECT HERE
DO NOT ALLOW SELECT FOR THIS
SHOW ALL LISTED CAPTIONS

我想要的是单击每个按钮,让我在我的文本区域中得到的值为:

在选择->允许此处选择

     A100104  ,Z100104  ,S100104  ,Q100104  ,D100104  ,D100104  ,D100104

选择->请勿为此选择

     XX223366  ,XX243356  ,XX323356  ,XX228866  ,XX220066  ,XX423366  ,XX423366

选择->显示所有列出的字幕

    XX223366  ,XX243356  ,XX323356  ,XX228866  ,XX220066  ,XX423366  ,XX423366, A100104  ,Z100104  ,S100104  ,Q100104  ,D100104  ,D100104  ,D100104

并且在optgroup label =“ ELSE SELECT ONE OR MULTIPLE”下,需要将一个或多个值显示为:

A100104  ,Z100104  ,S100104
A100104

虽然我可以提取

var stre = "LKICaption-D100104  [ALLOW SELECT HERE]"
var str2 = stre.split('-');
var strval = str2[str2.length - 1];
//alert(strval) // D100104  [ALLOW SELECT HERE]

alert(strval.split(' ')[0]) // Worked this way o/p is D100104

或让我知道如果这不是正确的设计方法并无法获得理想的结果,我将根据其他任何设计建议进行工作。谢谢

0 个答案:

没有答案