【发布时间】:2020-05-24 15:07:09
【问题描述】:
我有一个初始下拉菜单,我想在其中选择一个值:
<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>
选择不同的值时,它运行更新器()函数,该函数使用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 字段,而不是标准的选择下拉菜单?
谢谢
这是被调用的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>";
【问题讨论】:
-
showError( mysqli_query( $conn, $query ) )mysqli_error($conn)。你有一个名为showError()的函数? -
@pet 3v4l.org/91XZr 如果您使用的是版本 4 stackoverflow.com/q/25428361/2943403,则更简单
标签: javascript php jquery jquery-select2