gpt4 book ai didi

php - 如何使用 Javascript 在下拉列表中显示选项名称

转载 作者:行者123 更新时间:2023-11-29 02:56:56 25 4
gpt4 key购买 nike

我有两个下拉菜单,其中的值是从 MySQL 填充的。第二个下拉值取决于第一个下拉选项。

无论如何,代码是有效的。现在使用我的代码将 hospital_id 发布到另一个 php。但我也想在下拉列表中显示医院名称作为文本,但截至目前我只能显示医院 ID。

请看下面的代码并给我一个解决方案:

$query = "SELECT bp_id,bp_name FROM mfb_billing";
$result = $db->query($query);

while($row = $result->fetch_assoc()){
$categories[] = array("bp_id" => $row['bp_id'], "val" => $row['bp_name']);
}

$query = "SELECT bp_id, hospital_id, hospital_name FROM mfb_hospital";
$result = $db->query($query);

while($row = $result->fetch_assoc()){
$subcats[$row['bp_id']][] = array("bp_id" => $row['bp_id'], "val" => $row['hospital_id']);
}

$jsonCats = json_encode($categories);
$jsonSubCats = json_encode($subcats);

这是脚本:

<script type='text/javascript'>
<?php
echo "var categories = $jsonCats; \n";
echo "var subcats = $jsonSubCats; \n";
?>
function loadCategories(){
var select = document.getElementById("categoriesSelect");
select.onchange = updateSubCats;
for(var i = 1; i < categories.length; i++){
select.options[i] = new Option(categories[i].val,categories[i].bp_id);
}
}
function updateSubCats(){
var catSelect = this;
var catid = this.value;
var subcatSelect = document.getElementById("subcatsSelect");
subcatSelect.options.length = 0; //delete all options if any present
for(var i = 0; i < subcats[catid].length; i++){
subcatSelect.options[i] = new Option(subcats[catid][i].val,subcats[catid][i].hosp);
}
}
</script>

这是我的表格:

<body onload='loadCategories()'>
<form id="reportvalue" action="testpj2.php" method="post">

<select id='categoriesSelect'>
<option value="1">Select Billing Provider</option>
</select>

<select name='hospitalname[]' id='subcatsSelect' multiple='multiple'>
<option value="all">Select Billing Provider</option>
</select>
<label for="from">From</label>
<input type="text" id="from" name="from">
<label for="to">to</label>
<input type="text" id="to" name="to">
<?php
//$a = $_REQUEST['hospitalname[]'];
//echo $a;
?>
<input type="submit" name="Submit" value="Submit">
</form>

最佳答案

HTML

 <select id="someId"></select>

Javascript

 document.getElementById('someId').innerHTML="
<option value='value1'>"+option1+"</option>
<option value='value2'>"+option2+"</option>
<option value='value3'>"+option3+"</option>";

更新:

对于来自 SQL 查询的动态数据,

尝试在查询执行后放置这些代码。将 $row['value'] 和 $row['option'] 替换为受尊重的动态值。

 echo"<script type='text/javascript'> var str = '' </script>";
while($row = $result->fetch_assoc())
{
echo"<script type='text/javascript'>
str = str + '<option value='+".$row['value']."+'>'+".$row['option']."+'</option>
</script>";
}
echo"<script type='text/javascript'>
document.getElementById('someId').innerHTML = str
</script>";

关于php - 如何使用 Javascript 在下拉列表中显示选项名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29816107/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com