我想使用 jQuery 来填充第二个选择框和一个文本字段。当在第一个中进行选择时,我有第二个选择框被正确填充。不过,我无法让它填充文本字段。
数据是从 MySQL 数据库中检索的。下面是我为第一个选择框工作以在第二个中进行选择的代码。
我的 jQuery 代码:
<script>
$(document).ready(function(){
$("#shipment").change(function() {
$("#vender").load("selection.php", $("#shipment"));
}).trigger("change");
});
</script>
与此相关的表单字段:
<html>
<label for="shipments">Shipment: </label><select id="shipment" name="shipment_id">
<?php if(isset($shipment_selection)) { echo $shipment_selection; } ?> //echos options from db.
</select>
<label for="vender">Vender: </label><select id="vender" name="vender_id"></select>
<label for="cost">Cost: </label>><input type="text" id="cost" name="cost" value="" />
</html>
获取数据的 PHP 脚本:
<?php
include('../scripts/db_config.php');
if(isset($_POST['shipment_id'])) {
if($_POST['shipment_id'] == 1) {
$sql = 'SELECT id AS vender_id, name AS vender_name FROM venders'; //shows all venders, when shipment is none.
}
else {
$sql = 'SELECT venders.id AS vender_id, venders.name AS vender_name, shipment.qty AS qty, shipment.cost AS cost FROM shipments INNER JOIN venders ON venders.id=shipments.vender_id WHERE shipments.id='.$_POST['shipment_id']; //Select vender associated with specific shipment.
}
$stmt = $db->query($sql);
$data = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$data[] = $row;
//echo '<option value="'.$row['vender_id'].'">'.$row['vender_name'].'</option>'; //populates second select box.
}
echo json_encode($data);
}
完成这项工作后,我将更好地保护 PHP 代码。
关于如何在第一个选择框中进行选择以填充第二个选择框的任何建议,并且文本字段会很棒。
如果格式关闭,请道歉;我是盲人,所以我不确定它在屏幕上的实际外观。