我有两个下拉菜单,第一个下拉菜单的选择可以正确填充第二个下拉菜单。我已经使用ajax-php成功实现了它。
现在我尝试使用selectize.js ,应用于第一个 select
(第一个下拉列表),它按预期正常工作,但第二个下拉列表未正确填充。我已经阅读了文档(这不是我读过的最好的文档),并且我认为默认情况下 selectize.js 无法处理元数据。
但是有一个 addOption()
和一个 addItem()
方法是我应该实现的。我的问题是我找不到解析的方法ajax-php 给出的结果(并在第二个下拉列表中存储为 options
)并正确使用它们...
PHP 代码
echo "<select name='universities' id='universities' ></select>"; //Here is where the second dropdown is populated properly
JQuery 代码更新第二个下拉列表
//Successfully the second dropdown is populated before
$("#universities").selectize();
//If i change the first dropdown option now,the second dropdown remains the same
//if i comment $("#universities").selectize(); line everything works fine.
有什么想法吗?
最佳答案
尝试此示例并更新您的查询
HTML
// first drop down menu
<select id="city" name="city">
<option value="">Select City</option>
<option value="1">Cairo</option>
<option value="2">Alexandria</option>
<option value="3">Tanta</option>
</select>
// Second drop down menu you want to populate it depending on the choosing from first drop down menu
<select id="universities" name="universities"></select>
JAVASCRIPT
<script>
$("#city").change(function() {
var city_id = $(this).val();
var selectize = $("#universities")[0].selectize;
$.ajax({
url: '/gitUniversities.php',
type: 'GET',
dataType: 'json',
data: {
city_id: city_id,
},
error: function(response) {
selectize.clear();
selectize.clearOptions();
selectize.disable();
},
success: function(response) {
console.log(response);
//alert(response);
selectize.enable();
selectize.clear();
selectize.clearOptions();
selectize.load(function(callback) {
callback(response.data);
});
}
});
});
$('#universities').selectize({
valueField: 'key',
labelField: 'value',
searchField: 'value',
options: [],
create: false,
render: {
option: function(data, escape) {
return '<div class="option">' + escape(data.value) +'</div>';
}
}
});
</script>
PHP
gitUniversities.php 文件
// city_id came from ajax request
$city_id = $_GET['city_id'];
// your query to select from table `universities` where the city = city_id
$universities = SELECT `id` as 'key',`name` as 'value' FROM `universities` WHERE `city_id` = $city_id;
// return data as json
return json_encode(['data' => $universities, 'status' => true]);
它现在应该可以和你一起工作了
关于jquery - 使用 selectize.js 填充第二个下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21150161/