这里的任何帮助将不胜感激,因为我看不出我做错了什么。
我有一个空的选择器:
<select class='selectpicker' name='new_teamid' id='new_teamid' style='width:200px;margin-left:-5px;margin-top:0px;' required></select>
当另一个选择框选项发生更改时,将通过 AJAX 调用填充此内容
var query_parameter = document.getElementById("new_deptid").value;
var dataString = 'dept=' + query_parameter;
// AJAX code to execute query and get back to same page with table content without reloading the page.
$.ajax({
type: "POST",
url: "helpers/populateteams.php",
data: dataString,
cache: false,
success: function(html) {
document.getElementById("new_teamid").innerHTML=html;
$('#new_teamid').selectpicker('refresh');
}
});
正如您所看到的,它调用另一个 php 页面,该页面返回选项的 HTMl 字符串。这是可行的,如果我检查该元素,HTML 选项就会正确更新。我使用=而不是+=。问题是,选择选择器没有删除以前的项目。它只是不断添加新项目。
知道我在这里做错了什么吗?
如果您好奇,这是 populateteams.php
$theHTML = "";
$theHTML .= '<option value="" selected>Please Select</option>';
$sql = "SELECT * FROM tool_teams WHERE (dept_id=?) ORDER BY teamname asc";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $dept_id);
if ($stmt->execute() === TRUE) {
$result = $stmt->get_result();
if(!empty($result) && $result->num_rows)
{
while ($row = mysqli_fetch_array($result))
{
$theHTML .= '<option value="'.$row['team_id'].'">'.$row['teamname'].'</option>';
}
}
}
echo $theHTML;
最佳答案
我自己解决了这个问题。这很愚蠢,但您需要这样做:
$.ajax({
type: "POST",
url: "helpers/populateteams.php",
data: dataString,
cache: false,
success: function(html) {
document.getElementById("new_teamid").innerHTML=html;
$('#new_teamid').selectpicker('destroy');
$('#new_teamid').selectpicker('render');
},
complete: function(html) {
}
});
您需要销毁并渲染而不是刷新。这太愚蠢了。但它有效
关于ajax - Bootstrap Select 'refresh"继续添加新选项而不是删除旧选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72386080/