# Tạo chức năng tự động hoàn tất nhập liệu với thư viện jQuery UI Autocomplete (Phần 1)

Hàng ngày, các bạn thường sử dụng Google để tìm kiếm thông tin, và khi các bạn gõ bất kì từ khóa nào thì Google sẽ tự động liệt kê danh sách những cụm từ có nghĩa tương đồng với từ khóa đó ở bên dưới để gợi ý cho các bạn. Điều này sẽ giúp các bạn rút ngắn thời gian gõ toàn bộ từ khoá, đồng thời cũng giúp các bạn nhập vào chính xác từ khóa cần tìm hơn. Đây là một chức năng hay mà các website thường sử dụng và để thực hiện được chức năng này tôi giới thiệu với các bạn thư viện jQuery UI Autocomplete trong bộ thư viện jQuery UI.\
\
Để sử dụng thư viện jQuery UI các bạn cần phải tích hợp thư viện jQuery. Các bạn tải thư viện jQuery tại địa chỉ <http://jquery.com/download>. Ngoài ra, trong gói thư viện jQuery UI cũng đã có sẵn thư viện jQuery để các bạn tích hợp.\
\
Các bạn tải gói thư viện jQuery UI tại địa chỉ <http://jqueryui.com/download>. Tại trang tải thư viện, các bạn có thể chọn các thành phần mà các bạn cần dùng cũng như chọn mẫu giao diện các bạn muốn sử dụng, với bài viết này thì tôi chỉ sử dụng duy nhất thành phần Autocomplete.\
\
Các bạn tích hợp thư viện jQuery UI vào website với nội dung mã lệnh như sau:\
HTML:

```
<link href="path/to/jquery-ui.min.css" rel="stylesheet">
<script src="path/to/jquery-ui.min.js"></script>
```

Và cài đặt thư viện jQuery UI Autocomplete với nội dung mã lệnh như sau:\
JavaScript:

```
$(function() {
    $('#autocomplete').autocomplete({
        source: ['One', 'Two', 'Three']
    });
});
```

Sau đó để áp dụng tự động hoàn tất nhập liệu với trường nào đó các bạn tham khảo ví dụ sau:\
HTML:

```
<input type="text" name="autocomplete" id="autocomplete">
```

Các bạn có thể tìm hiểu thêm về thư viện jQuery UI Autocomplete tại địa chỉ <http://jqueryui.com/autocomplete>.

```
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Autocomplete - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.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>
  $( function() {
    var availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "C",
      "C++",
      "Clojure",
      "COBOL",
      "ColdFusion",
      "Erlang",
      "Fortran",
      "Groovy",
      "Haskell",
      "Java",
      "JavaScript",
      "Lisp",
      "Perl",
      "PHP",
      "Python",
      "Ruby",
      "Scala",
      "Scheme"
    ];
    $( "#tags" ).autocomplete({
      source: availableTags
    });
  } );
  </script>
</head>
<body>
 
<div class="ui-widget">
  <label for="tags">Tags: </label>
  <input id="tags">
</div>
 
 
</body>
</html>
```

Ví dụ 1:

{% embed url="<https://index.php>" %}

```
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Demo</title>
  <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/themes/base/minified/jquery-ui.min.css" type="text/css" /> 
  <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
	<script type="text/javascript" src="http://code.jquery.com/ui/1.10.1/jquery-ui.min.js"></script>	
</head>
<body> 
<form method='post'>
	<p>
		<label>Country:</label>
		<input type='text' name='country' value='' class='auto'>
	</p>
</form>
<script type="text/javascript">
	$(function() {
		$(".auto").autocomplete({
			source: "search.php",
			minLength: 1
		});				
	});
</script>
</body>
</html>
```

{% embed url="<https://search.php>" %}

```
<?php
define('DB_SERVER', 'localhost');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'autocomplete');
if (isset($_GET['term'])) {
  $return_arr = array();
  try {
    $conn = new PDO("mysql:host=" . DB_SERVER . ";port=3306;dbname=" . DB_NAME, DB_USER, DB_PASSWORD);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare('SELECT country FROM countries WHERE country LIKE :term');
    $stmt->execute(array('term' => '%' . $_GET['term'] . '%'));
    while ($row = $stmt->fetch()) {
      $return_arr[] = $row['country'];
    }
  } catch (PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
  }
  echo json_encode($return_arr);
}
?>
```

{% file src="<https://2494213435-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LYjAG13rAPdbArSfRyB%2F-M9lUv-OGEpnBiNnp89N%2F-M9lY9KgUGvn4w_Z_jcr%2Fautocomplete.zip?alt=media&token=c1fc6108-47b1-42c4-b05b-5ea964677d83>" %}

Ví dụ 2:

index.php

```
<!DOCTYPE html>
<html>

<head>
  <title>Bootstrap Autocomplete with Dynamic Data Load using PHP Ajax</title>
  <link href="http://localhost/library/bootstrap/css/bootstrap.min.css" rel="stylesheet">
  <link href="http://localhost/library/jquery-ui/jquery-ui.min.css" rel="stylesheet">
  <script type="text/javascript" src="http://localhost/library/jquery/jquery.min.js"></script>
  <script type="text/javascript" src="http://localhost/library/jquery-ui/jquery-ui.min.js"></script>	
  <style>
    .autocomplete {
	  border: 2px solid #FFF;
	  border-radius: 4px;
	  padding: 8px 12px;
	  max-width: 300px;
	  min-width: 290px;
	  background: rgba(66, 52, 52, 0.5);
	  color: #FFF;
	}
	 .tt-menu {
	   width: 300px;
	 }

	 ul.autocomplete {
	   margin: 0px;
	   padding: 10px 0px;
	 }

	 ul.autocomplete.dropdown-menu li a {
	   padding: 10px !important;
	   border-bottom: #CCC 1px solid;
	   color: #FFF;
	 }

	 ul.autocomplete.dropdown-menu li:last-child a {
	   border-bottom: 0px !important;
	 }

	 .bgcolor {
	   max-width: 550px;
	   min-width: 290px;
	   max-height: 340px;
	   background: url("world-contries.jpg") no-repeat center center;
	   padding: 100px 10px 130px;
	   border-radius: 4px;
	   text-align: center;
	   margin: 10px;
	 }

	 .demo-label {
	   font-size: 1.5em;
	   color: #686868;
	   font-weight: 500;
	   color: #FFF;
	 }

	 .dropdown-menu>.active>a,
	 .dropdown-menu>.active>a:focus,
	 .dropdown-menu>.active>a:hover {
	   text-decoration: none;
	   background-color: #1f3f41;
	   outline: 0;
	 }
</style>
</head>

<body>
  <div class="bgcolor">
    <label class="demo-label">Search Country:</label>
    <br /> 
    <input type="text" name="txtCountry" id="txtCountry" class="autocomplete" />
  </div>
</body>
<script>
$(document).ready(function() {
  $('#txtCountry').autocomplete({
    source: function(query, result) {
      $.ajax({
        url: "server.php",
        data: 'query=' + query.term,
        dataType: "json",
        type: "POST",
        success: function(data) {
          result($.map(data, function(item) {
            return item;
          }));
        }
      });
    }
  });
});
</script>

</html>
```

{% embed url="<https://server.php>" %}

```
<?php
$keyword      = strval($_POST['query']);
$search_param = "{$keyword}%";
$conn         = new mysqli('localhost', 'root', '', 'autocomplete');
$sql          = $conn->prepare("SELECT * FROM tbl_country WHERE country_name LIKE ?");
$sql->bind_param("s", $search_param);
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows > 0) {
  while ($row = $result->fetch_assoc()) {
    $countryResult[] = $row["country_name"];
  }
  echo json_encode($countryResult);
}
$conn->close();
?>
```

{% file src="<https://2494213435-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LYjAG13rAPdbArSfRyB%2F-M9lYNmXFVQA7e_HfBIw%2F-M9lflfHaoujZxkS9Y7v%2Fautocomplete.zip?alt=media&token=0e1f8c41-5c1c-4edd-b83e-5045bcf0b54e>" %}

Ví dụ 3:

index.html

```
<!doctype html>
<html>

<head>
  <title>jQuery UI autocomplete with PHP and AJAX</title>
  <script src='jquery-3.1.1.min.js' type='text/javascript'></script>
  <link href='jquery-ui.min.css' rel='stylesheet' type='text/css'>
  <script src='jquery-ui.min.js' type='text/javascript'></script>
</head>

<body>
  <table>
    <tr>
      <td>Single selection</td>
      <td><input type='text' id='autocomplete'></td>
    </tr>
    <tr>
      <td>Selected User id</td>
      <td><input type='text' id='selectuser_id' /></td>
    </tr>
    <tr>
      <td>Multiple Selection</td>
      <td><input type='text' id='multi_autocomplete'></td>
    </tr>
    <tr>
      <td>Selected User ids</td>
      <td><input type='text' id='selectuser_ids' /></td>
    </tr>
  </table>
  <script type='text/javascript'>
  $(function() {
    $("#autocomplete").autocomplete({
      source: function(request, response) {
        $.ajax({
          url: "fetchData.php",
          type: 'post',
          dataType: "json",
          data: {
            search: request.term
          },
          success: function(data) {
            response(data);
          }
        });
      },
      select: function(event, ui) {
        $('#autocomplete').val(ui.item.label);
        $('#selectuser_id').val(ui.item.value);
        return false;
      }
    });
    $("#multi_autocomplete").autocomplete({
      source: function(request, response) {
        var searchText = extractLast(request.term);
        $.ajax({
          url: "fetchData.php",
          type: 'post',
          dataType: "json",
          data: {
            search: searchText
          },
          success: function(data) {
            response(data);
          }
        });
      },
      select: function(event, ui) {
        var terms = split($('#multi_autocomplete').val());
        terms.pop();
        terms.push(ui.item.label);
        terms.push("");
        $('#multi_autocomplete').val(terms.join(", "));
        var terms = split($('#selectuser_ids').val());
        terms.pop();
        terms.push(ui.item.value);
        terms.push("");
        $('#selectuser_ids').val(terms.join(", "));
        return false;
      }
    });
  });

  function split(val) {
    return val.split(/,\s*/);
  }

  function extractLast(term) {
    return split(term).pop();
  }
  </script>
</body>

</html>
```

{% embed url="<https://config.php>" %}

```
<?php
session_start();
$host     = "localhost";
$user     = "root";
$password = "";
$dbname   = "tutorial";
$con      = mysqli_connect($host, $user, $password, $dbname);
if (!$con) {
  die("Connection failed: " . mysqli_connect_error());
}
```

{% embed url="<https://fetchData.php>" %}

```
<?php
include "config.php";
if (isset($_POST['search'])) {
  $search = $_POST['search'];
  $query  = "SELECT * FROM users WHERE name like'%" . $search . "%'";
  $result = mysqli_query($con, $query);
  while ($row = mysqli_fetch_array($result)) {
    $response[] = array("value" => $row['id'], "label" => $row['name']);
  }
  echo json_encode($response);
}
exit;
```

{% file src="<https://2494213435-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LYjAG13rAPdbArSfRyB%2F-M9lgZUupuoym78UKM23%2F-M9ljb8XHOY0SMSnWJOs%2Fautocomplete.zip?alt=media&token=02e57998-95f6-4ae2-a200-815005880d95>" %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://javascriptuse.gitbook.io/javascript/tao-chuc-nang-tu-dong-hoan-tat-nhap-lieu-voi-thu-vien-jquery-ui-autocomplete.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
