问题描述
我尝试用json文件中的数据填充选择表单.
I try to populate a select form with data from a json file.
[{"matricola":"1", "nome":"aaaaa"},{"matricola":"2", "nome":"bbbbbb"}]
如果我使用select可以正常工作,如果我尝试使用selectpicker,我将无法理解我必须在JavaScript代码中刷新selectpicker的位置.
If I use select it works, if i try to use selectpicker I do not understand where I have to refresh the selectpicker in my javascript code.
这是我的代码:
<div class="form-group ">
<select id="cf" class="selectpicker show-tick form-control" data-dropup-auto="false" data-live-search="true" required="" name="cf">
</select>
</div>
<script>
let dropdown = document.getElementById('cf');
dropdown.length = 0;
let defaultOption = document.createElement('option');
defaultOption.text = 'Seleziona un dipendente';
dropdown.add(defaultOption);
dropdown.selectedIndex = 0;
const url = 'tables/griglia_dipendenti_incarichi.php';
const request = new XMLHttpRequest();
request.open('GET', url, true);
request.onload = function() {
if (request.status === 200) {
const data = JSON.parse(request.responseText);
let option;
for (let i = 0; i < data.length; i++) {
option = document.createElement('option');
option.text = data[i].nome;
option.value = data[i].matricola;
if (i==0){
alert(option.text);
}
dropdown.add(option);
}
} else {
// Reached the server, but it returned an error
}
}
request.onerror = function() {
console.error('An error occurred fetching the JSON from ' + url);
};
request.send();
</script>
我尝试过
dropdown.add(option).selectpicker('refresh');
但没有用
推荐答案
首先,您应该阅读本指南- https://developer.snapappointments.com/bootstrap-select/并检查是否已将所有需要的文件链接到该页面.
接下来是初始化Bootstrap-select插件.您可以对页面上的所有选择标签执行此操作:
Firstly you should read this guide - https://developer.snapappointments.com/bootstrap-select/ and check if you have linked all needed files to the page.
Next thing is to initialize Bootstrap-select plugin. You can do it for all select tags on the page:
$('select').selectpicker();
或仅针对您的元素:
$('#cf').selectpicker();
现在,如果您更改任何选择并希望用户看到更改,则需要刷新selectpicker插件.
如果您使用新版本的Bootstrap-select插件,请尝试以下操作:
Now, if you change any select and want a user to see changes, you need to refresh selectpicker plugin.
If you use a new version of Bootstrap-select plugin, then try this:
$('#cf').selectpicker('refresh');
否则使用此:
$('#cf').selectpicker('destroy');
$('#cf').selectpicker();
ps:这是一个简单的示例- https://jsfiddle.net/Denisdude/pf7qreum/17/
p.s.: here's a simple exapmle - https://jsfiddle.net/Denisdude/pf7qreum/17/
这篇关于selectpicker('refresh')的sintax问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!