douya7282
douya7282
2018-08-03 08:02

jQuery自动完成,通过选择建议的选项填充多个字段

  • autocomplete
  • php
  • jquery

I have autocomplete jQuery script working for pulling suggestions from MySQL database when typing in form fields on the page (3 input fields). That is working fine, but what I would like is to when I select suggested option in the first field - all 3 fields should be filled. Fields that I have right now is first name, last name, and company. When I select the first name - last name and company should be automatically filled with data.

Here's 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>

And here's the autocomplete.php file:

<?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);
?>

So, when the suggested option from "first_name" is selected - "last_name" and "company" should be filled with corresponding data from a database. Any suggestions?

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答

为你推荐