Bootstrap选择不允许选择所有内容

时间:2017-01-10 23:26:13

标签: javascript html twitter-bootstrap

我想使用bootstrap select。我有两个选项叫"已连接"和"检测到"。它是一个多选,即我可以使用连接,检测或两者。

这是代码:

HTML

<select id="connectedDetected" class="selectpicker col-xs-4" multiple="multiple" data-live-search="true" title="Connected, Detected"/>

使用Javascript:

        var connectedDetected =
          [ {
              "key" : "connected",
              "title" : "Connected"
            }, {
              "key" : "detected",
              "title" : "Detected"
            }
          ],

          output = '';

          connectedDetected.forEach(function(tag){
              var selected = 'selected="true"';

              output += '<option value="'+ tag.key +'" '+selected+'>'+ tag.title +'</option>';
          });

        this.ui.connectedDetected.append(output);

        this.ui.connectedDetected.selectpicker({
          multiple:true,
          size: 2
        });

问题:

如何在bootstrap select中强制选择至少一个选项? I.e我不希望用户取消选择所有内容。 我想要同时检查两个或一个选项(已连接或检测到或两者)?

谢谢,

1 个答案:

答案 0 :(得分:0)

var connectedDetected =
          [ {
              "key" : "connected",
              "title" : "Connected"
            }, {
              "key" : "detected",
              "title" : "Detected"
            }
          ],

          output = '';

$(connectedDetected).each(function(i,j){
  output += "<option value='"+ j.key + "' selected>"+ j.title + "</option>";
});

$("#mySelect").html(output);

function check(){
  if($("#mySelect").find(":selected").length==0)
    $("#mySelect option:first").attr("selected","selected");

  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
For to select multiple press and hold CTRL while clicking<br>
<select id="mySelect" multiple size=2 onchange="check()"></select>
  
 </body>