twitter-bootstrap Bootstrap-select 不适用于动态填充的选项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32681437/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 23:11:03  来源:igfitidea点击:

Bootstrap-select not working with dynamically populated options

jquerytwitter-bootstrap

提问by lostintheriver

'use strict';
var PS = (function(){
var municipes = [{
 "cod_prov": "01",
 "cod_mun": "001",
 "id": 0,
 "name": "Alegría-Dulantzi"
}, {
   "code": "47",
   "name": "VALLADOLID"
  }, {
   "code": "48",
   "name": "BIZKAIA"
  }, {
   "code": "49",
   "name": "ZAMORA"
  }, {
   "code": "50",
   "name": "ZARAGOZA"
  }, {
   "code": "51",
   "name": "CEUTA"
  }, {
   "code": "52",
   "name": "MELILLA"
  }];

var provinceCssSelector = '.ps-prov';
var municipeCssSelector = '.ps-mun';
var provinceDefaultText = 'Provincia';
var municipeDefaultText = 'Municipio';


$().ready(function() {
 // Set default text
 $(provinceCssSelector).append($('<option>').text(provinceDefaultText).attr('value', -1));
 $(municipeCssSelector).append($('<option>').text(municipeDefaultText).attr('value', -1));

 // Populate province select
 $.each(provinces, function(number, province) {
  $(provinceCssSelector).append($('<option>').text(province.name).attr('value', province.code));
 });

 // When selected province changes, populate municipe select
 $(provinceCssSelector).change(function() {
  var selectedProvince = this.value;
  $(municipeCssSelector).empty();
  $(municipeCssSelector).append($('<option>').text(municipeDefaultText).attr('value', -1));
  $.each(municipes, function(number, municipe) {
   if (municipe.cod_prov == selectedProvince) {
    $(municipeCssSelector).append($('<option>').text(municipe.name).attr('value', number.toString()));
     
   }
   
  });
  
   
  
 });
 $('.selectpicker').selectpicker('refresh');
 
 
 
});

}());
<html lang="en">
<head>
 
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
     
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 
</head>
<body>

 
           
  <tr>
            <td>Select where happenings occurred</td>
            <td>
   
   <select id="province" name="province" class="ps-prov selectpicker show-tick form-control" data-live-search="true" ></select>

  
   
  </td>
        </tr>
   
  <tr>
            <td>Select city</td>
            <td>
   
   <select id="city" name="city" class="ps-mun selectpicker show-tick form-control" data-live-search="true"></select>
   </td>
   
   </tr>
  
  
  
  
 
  
  
 
    </table>
 
</form>


 </div>

</html>

I am trying to use bootstrap-select to improve the style of one my projects but when the options of the select are built dynamically the plugin does not work and I do not find the error. I have included the $('.selectpicker').selectpicker('refresh');as proposed by this answerbut still I am not able to achieve what I want. The HTML is the following and works perfectly:

我正在尝试使用 bootstrap-select 来改进我的项目的风格,但是当动态构建选择的选项时,插件不起作用,我没有发现错误。我已经包括了$('.selectpicker').selectpicker('refresh');这个答案所提出的, 但我仍然无法实现我想要的。HTML如下并且完美运行:

<tr>
  <td>Select where happenings occurred</td>
  <td>
    <select id="province" name="province" class="ps-prov selectpicker show-tick form-control" data-live-search="true"></select>
  </td>
</tr>
<tr>
  <td>Select city</td>
  <td>
    <select id="city" name="city" class="ps-mun selectpicker show-tick form-control" data-live-search="true"></select>
  </td>
</tr>

The javascript works in the following way

javascript按以下方式工作

var provinceCssSelector = '.ps-prov';
var municipeCssSelector = '.ps-mun';
var provinceDefaultText = 'Provincia';
var municipeDefaultText = 'Municipio';


$().ready(function() {
  // Set default text
  $(provinceCssSelector).append($('<option>').text(provinceDefaultText).attr('value', -1));
  $(municipeCssSelector).append($('<option>').text(municipeDefaultText).attr('value', -1));

  // Populate province select
  $.each(provinces, function(number, province) {
    $(provinceCssSelector).append($('<option>').text(province.name).attr('value', province.code));
  });

  // When selected province changes, populate municipe select
  $(provinceCssSelector).change(function() {
    var selectedProvince = this.value;
    $(municipeCssSelector).empty();
    $(municipeCssSelector).append($('<option>').text(municipeDefaultText).attr('value', -1));
    $.each(municipes, function(number, municipe) {
      if (municipe.cod_prov == selectedProvince) {
        $(municipeCssSelector).append($('<option>').text(municipe.name).attr('value', number.toString()));
      }
    });
    $('.selectpicker').selectpicker('refresh');
  });
});

Does anyone know how to make the combo select works?

有谁知道如何使组合选择有效?

采纳答案by Romulo

The problem here is that the plugin bootstrap-select is creating a new element (div) that has every class from your original element (select).

这里的问题是插件 bootstrap-select 正在创建一个新元素 (div),它具有原始元素 (select) 中的每个类。

So when your code tries to append the options in the select using the css selector, you are both appending in the original element (select) and in the element that the plugin created (div), causing the erratic behavior.

因此,当您的代码尝试使用 css 选择器在 select 中附加选项时,您将同时附加到原始元素 (select) 和插件创建的元素 (div) 中,从而导致不稳定的行为。

You have many ways to prevent this behavior, one is to use the ID selector for example.

您有很多方法可以防止这种行为,例如使用 ID 选择器。

Here's a snippet a possible solution:

这是一个可能的解决方案的片段:

var provinceCssSelector = '#province';
var municipeCssSelector = '#city';
var provinceDefaultText = 'Provincia';
var municipeDefaultText = 'Municipio';

var provinces = [{
  name: '1',
  code: 1
}, {
  name: '2',
  code: 2
}, {
  name: '3',
  code: 3
}];

var municipes = [{
  name: '1-1',
  cod_prov: 1
}, {
  name: '1-2',
  cod_prov: 1
}, {
  name: '1-3',
  cod_prov: 1
}, {
  name: '2-1',
  cod_prov: 2
}, {
  name: '2-2',
  cod_prov: 2
}, {
  name: '2-3',
  cod_prov: 2
}, {
  name: '3-1',
  cod_prov: 3
}, {
  name: '3-2',
  cod_prov: 3
}, {
  name: '3-3',
  cod_prov: 3
}];

$().ready(function() {

  // Set default text
  $(provinceCssSelector).append($('<option>').text(provinceDefaultText).attr('value', -1));
  $(municipeCssSelector).append($('<option>').text(municipeDefaultText).attr('value', -1));

  // Populate province select
  $.each(provinces, function(number, province) {
    $(provinceCssSelector).append($('<option>').text(province.name).attr('value', province.code));
  });

  // When selected province changes, populate municipe select
  $(provinceCssSelector).change(function() {
    var selectedProvince = this.value;
    $(municipeCssSelector).empty();
    $(municipeCssSelector).append($('<option>').text(municipeDefaultText).attr('value', -1));
    $.each(municipes, function(number, municipe) {
      if (municipe.cod_prov == selectedProvince) {
        $(municipeCssSelector).append($('<option>').text(municipe.name).attr('value', number.toString()));
      }
    });
    $(municipeCssSelector).selectpicker('refresh');
    $(municipeCssSelector).selectpicker('render');
  });
});
<link rel="stylesheet" href="http://getbootstrap.com/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="http://silviomoreto.github.io/bootstrap-select/bootstrap-select.min.css">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://getbootstrap.com/dist/js/bootstrap.min.js"></script>
<script src="http://silviomoreto.github.io/bootstrap-select/bootstrap-select.min.js"></script>

<table>
  <tr>
    <td>Select where happenings occurred</td>
    <td>
      <select id="province" name="province" class="ps-prov selectpicker show-tick form-control" data-live-search="true"></select>
    </td>
  </tr>
  <tr>
    <td>Select city</td>
    <td>
      <select id="city" name="city" class="ps-mun selectpicker show-tick form-control" data-live-search="true"></select>
    </td>
  </tr>
</table>

Hope it helps!

希望能帮助到你!

回答by Rajdeep

I also had the same problem in my project but solved using below trick:

我在我的项目中也遇到了同样的问题,但使用以下技巧解决了:

In my Ajax successCallBack, I am trying to manipulate a drop down list having an id as reasonCodebased on dynamicId(value I get from the server) as follows:

在我的 中Ajax successCallBack,我试图操作一个下拉列表,其 idreasonCode基于dynamicId(我从服务器获得的值)如下:

$('#reasonCode option[value='+dynamicId+']').prop('selected', true);

but unfortunately this did not work until I added another line after this as follows:

但不幸的是,这并没有奏效,直到我在这之后添加了另一行,如下所示:

$('#reasonCode').selectpicker('refresh');

回答by vijay sahu

 $('.selectpicker').selectpicker('refresh');

I have tried this and it is working.

我已经试过了,它正在工作。