PHP项目,它与组一起使用select。我需要为optgroup动态添加选项,以避免页面刷新。
selectize的初始加载是这样的。
<select style="padding-left: 0px; height: 35px;" class="selectize col-md-11 post-tags" id="fact-tags" placeholder="Select tags" multiple="multiple">
<?php
$topic_result = mysqli_query($mysqli, "SELECT * FROM topic ORDER BY topic_name ASC");
while ($topic = mysqli_fetch_assoc($topic_result)) {
?>
<optgroup label="<?php echo $topic['topic_name'] ?>">
<?php
$tag_result = mysqli_query($mysqli, "SELECT * FROM sub_topic WHERE topic_id = '".$topic['id']."'");
while ($tag = mysqli_fetch_assoc($tag_result)) {
?>
<option value="<?php echo $tag['id'] ?>" alt="<?php echo $topic['topic_name'] ?>"><?php echo $tag['sub_topic_name'] ?></option>
<?php } ?>
</optgroup>
<?php }
?>
</select>
Selectize通过JS对该选择进行了详细说明。
$('#post-tags.selectize').selectize({
create: false,
sortField: 'optgroup',
searchField: ['text', 'optgroup']
});
现在,我想向optgroup添加一个额外的选项。我尝试了很多选择。这是我想到的。但是它不起作用。
添加新的子主题后,我将进行AJAX调用以获取所有主题和子主题,并尝试使用新数据刷新selectize。
var ajaxurl = 'includes/functions.php',
data = {'action': 'getTopicList'};
$.post(ajaxurl, data, function (response) {
response = JSON.parse(response);
var new_value_optgroup = '[';
for (var key in response) {
var keyPlus = parseInt(key) + 1;
if (keyPlus == response.length) {
new_value_optgroup += '{groupName: "' + response[key].id +'", label: "' + response[key].topic_name + '"}';
} else {
new_value_optgroup += '{groupName: "' + response[key].id +'", label: "' + response[key].topic_name +'"},';
}
}
new_value_optgroup += ']';
var ajaxurl = 'includes/functions.php',
data = {'action': 'getPostTags'};
$.post(ajaxurl, data, function (response) {
response = JSON.parse(response);
var new_value_options = '[';
for (var key in response) {
var keyPlus = parseInt(key) + 1;
if (keyPlus == response.length) {
new_value_options += '{itemGroup: "' + response[key].topic_id + '", itemValue: "' + response[key].id + '", itemName: "' + response[key].sub_topic_name + '"}';
} else {
new_value_options += '{itemGroup: "' + response[key].topic_id + '", itemValue: "' + response[key].id + '", itemName: "' + response[key].sub_topic_name + '"},';
}
}
new_value_options += ']';
$('#post-tags.selectize').selectize({
options: new_value_options,
optgroups: new_value_optgroup,
optgroupField: 'itemGroup', // refers to the group field in "options"
optgroupLabelField: 'label', // refers to the label field in "optgroups"
optgroupValueField: 'groupName', // refers to the value field in "optgroups"
valueField: 'itemValue',
labelField: 'itemName',
searchField: ['label', 'itemName']
});
});
});
如果有人有更好的解决方案,我很乐于尝试那些解决方案。除了重新加载所有选项外,没有任何方法可以添加新的子主题。