【问题标题】:jQuery autocomplete, fill multiple fields by selecting suggested optionjQuery自动完成,通过选择建议选项填充多个字段
【发布时间】:2019-01-11 01:41:21
【问题描述】:

我有自动完成 jQuery 脚本,用于在页面上输入表单字段(3 个输入字段)时从 MySQL 数据库中提取建议。 这很好,但我想要的是当我在第一个字段中选择建议的选项时 - 所有 3 个字段都应该填写。 我现在拥有的字段是名字、姓氏和公司。当我选择名字时 - 姓氏和公司应该自动填充数据。

这里是 php:

<html>
<head>
 <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">       
        <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
        <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript">
$(function() 
{
 $( "#first_name" ).autocomplete({
  source: 'autocomplete.php'
 });
});
$(function() 
{
 $( "#last_name" ).autocomplete({
  source: 'autocomplete.php'
 });
});
$(function() 
{
 $( "#company" ).autocomplete({
  source: 'autocomplete.php'
 });
});
</script>
</head>
<body>
<div id="wrapper">

<div class="ui-widget">
 <p>First name</p>
 <input type="text" id="first_name">
</div>

<div class="ui-widget">
 <p>Last name</p>
 <input type="text" id="last_name">
</div>

<div class="ui-widget">
 <p>Company</p>
 <input type="text" id="company">
</div>

</div>
</body>
</html>

这是 autocomplete.php 文件:

<?php

$host="localhost";
$username="user";
$password="password";
$databasename="dbname";

$connect=mysql_connect($host,$username,$password);
$db=mysql_select_db($databasename);

$searchTerm = $_GET['term'];

$select =mysql_query("SELECT * FROM jemployee WHERE first_name LIKE '%".$searchTerm."%'");
while ($row=mysql_fetch_array($select)) 
{
$spojeno = $row['first_name'] . ' ' . $row['last_name'] . ' ' . $row['kompanija'];
$data[] = $spojeno;
}
//return json data
echo json_encode($data);
?>

因此,选择“First_Name”的建议选项 - “Last_name”和“公司”应填充来自数据库的相应数据。有什么建议吗?

【问题讨论】:

    标签: php jquery autocomplete jquery-ui-autocomplete


    【解决方案1】:

    使用 Jquery 喜欢的东西:

    $(document).on('keyup', '#firstname', funtion(){ $.ajax({ type:"POST", url:"ajax.php", data:$("#firstname").val(); }, success:function (res){ $("#lastname").val(res.lastname); $("#company").val(res.company); }, )}; });

    还有 PHP ajax.php 文件:

    &lt;?php

    \\Select lastname, company with $_POST['data']

    echo json_endcode($result);

    应该检查并处理 ajax 响应。如果你能解决这个问题,请让它变得更好。

    【讨论】:

    • 谢谢。虽然不太确定应该在 Ajax 中放置什么,但对 Ajax 和 Jquery 不是很熟悉。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-14
    • 1970-01-01
    • 2018-01-31
    • 2012-09-01
    • 2017-10-29
    • 1970-01-01
    相关资源
    最近更新 更多