我在表单中使用自动填充功能。我从表格容器中获取了vessel_name。但我需要来自table vessel的vessel_name和vessel_id。我需要vessel_id将数据插入另一个表夹中。
<input type="text" id="vessel_name" placeholder="Vessel Name" class="form-control" name="nam">
<input type="hidden" id="vessel_id" class="form-control" name="id">
<script>
$(function() {
var availableTags = <?php include('vname.php'); ?>;
$("#vessel_name").autocomplete({
source: availableTags,
autoFocus:true,
minLength:2
});
});
</script>
vname.php
<?php
$connection = mysqli_connect("localhost","root","","vasishipping")or die("Error " . mysqli_error($connection));
//fetch vessel names from the vessel table
$sql = "select * from vessel";
$result = mysqli_query($connection, $sql) or die("Error " .mysqli_error($connection));
$dname_list = array();
while($row = mysqli_fetch_array($result))
{
$vname_list[] = $row['vessel_name'];
$vname_list[] = $row['vessel_id'];
}
echo json_encode($vname_list);
?>
答案 0 :(得分:0)
我认为你的availableTags
是一个1维数组
您可以使用键和值将该数组转换为对象数组:
var availableTags = [
{ key: "1", value: "ActionScript" },
{ key: "2", value: "AppleScript" },
{ key: "3", value: "Asp" }
];
并检索将select函数添加到自动完成选项的值:
$("#vessel_name").autocomplete({
source: availableTags,
autoFocus:true,
minLength:2,
select: function(event, ui) {
$("#vessel_name").val(ui.item.value);
$("#vessel_id").val(ui.item.key);
}
});
这里有一个example检索两个值
编辑:添加PHP更改以检索正确格式的availableTags
数组
应更改PHP部分以提供示例格式的JSON 只需在while循环中添加:
$vname = $row['vessel_name'];
$vid = $row['vessel_id'];
$variable[] = array( 'key' => "$vid", 'value' => "$vname" )
并将$variable
返回json_encode