我有一个初始下拉菜单,我想在其中选择一个值:
<select id="indexID" name="indexID" class="form-control" onChange="updateSector();" style="width:300px;">
<option value='' selected>Select and Index</option>
<option value='3'>AIM</option>
<option value='1'>FTSE 100</option>
<option value='2'>FTSE 250</option>
</select>
选择其他值时,它将运行updateSector()函数,该函数使用ajax脚本加载与所选类别相关的所有扇区。然后,页面investment_sectors的输出将显示在页面上的标签中。
function updateSector(){
<? if ($sectorID<>""){?>
var sectorID = <?=$sectorID?>;
<? }else{?>
var sectorID = "";
<?}?>
var indexID = document.getElementById("indexID");
var indexID = indexID.options[indexID.selectedIndex].value;
var dataString = 'indexID=' + indexID +'§orID=' + sectorID;
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "investment_sectors.php",
data: dataString,
cache: false,
success: function(html) {
//alert(html);
document.getElementById("sector").innerHTML = html;
}
});
}
如果我要生成扇区的标准选择下拉列表,则所有这些都可以使用。但是由于有很多部门,我确实想要一个select2字段。
通常,如果我只是在标准页面中包括select2字段,我会将这个脚本添加到底部以加载我想要预选的任何传递值。但是,由于标签是空的,直到选择了一个选项并传递回去,所以没有内容可填充。
<script>
$(document).ready(function() {
$('.js-example-basic-single').select2();
});
$(document).ready(function() {
var select2single = $('.js-example-basic-single').select2({
placeholder: "Please Select",
width: '400px',
multiple: false,
})
select2single.val([<?=$sectorID?>]);
select2single.trigger("change");
});
</script>
有人可以帮助我修改我的代码以生成此select2字段,而不是标准的select下拉列表吗?
谢谢
这是被称为investment_sector页面的代码:
$sectorID=$_REQUEST['sectorID'];
$indexID=$_REQUEST['indexID'];
switch ($indexID){
case "1":
$sectorlist = "FTSE";
break;
case "2":
$sectorlist = "FTSE";
break;
case "3":
$sectorlist = "AIM";
break;
default:
$sectorlist = "";
}
$query = "SELECT * FROM tbl_sector WHERE sectorlist='".$sectorlist."' order by sector ASC";
$result = mysqli_query( $conn, $query )or showError( mysqli_query( $conn, $query ) );
$num_rows = mysqli_num_rows( $result );
echo "<select class=\"js-example-basic-single js-states form-control\" id=\"sectorID\" name=\"sectorID\">";
if ($sectorID==""){
echo "<option value='' selected>Select a ".$sectorlist." sector</option> \n ";
}
$i = 0;
while ( $row = mysqli_fetch_array( $result ) ) {
if ( $sectorID == $row[ 'sectorID' ] ) {
echo "<option value='" . $row[ 'sectorID' ] . "' selected>".$row[ 'sectorlist' ]." - " . $row[ 'sector' ] . "</option> \n ";
} else {
echo "<option value='" . $row[ 'sectorID' ] . "'>".$row[ 'sectorlist' ]." - " . $row[ 'sector' ] . "</option>\n";
}
$i++;
}
echo "</select>";
答案 0 :(得分:1)
问题在于,仅在文档准备好后才初始化select2。对于之后在DOM中创建的元素,即使它们具有相同的类,也不会自动发生。完成ajax后,应为新元素重新启动select2。试试这个:
$.ajax({
type: "POST",
url: "investment_sectors.php",
data: dataString,
cache: false,
success: function(html) {
//alert(html);
document.getElementById("sector").innerHTML = html;
$('#' + sectorID).select2();
}
});