javascript
javascript
javascript
  • Lấy vị trí người dùng với javascript
  • [Problem] Lấy key đầu tiên tìm thấy chứa giá trị cần tìm (ok)
  • 🥸Đoạn mã JavaScript để thêm ký tự đặc biệt vào đầu mỗi dòng trong văn bản nhiều dòng (ok)
  • 😍Tạo ra font in đậm và copy đến website để sử dụng (ok)
  • Hiệu ứng mở sách cực đẹp
  • 🤩JS: Scroll Animation using Intersection Observer API 🤩 (ok)
  • 😅Draw svg on scroll Full (ok)
  • 😄Install Linguise on any domain dịch tự động (ok)
  • 😅Sử dụng ajax tạo popup cho các bài viết wordrpess mattervn.com (ok)
  • 😆PWA - beforeinstallprompt toplusgames.com (ok)
  • How to Use the HTML5 Full-Screen API (Again) (ok)
  • [ERROR GAME] fix lỗi không load iframe gamedistribution.com for toplusgames.com (ok)
  • 😅jQuery Plugin To Create Animated Placeholders - placeholderTypewriter (ok)
  • 😍Làm chức năng thông báo khách hàng đăng ký namkhoahanoi.vn (ok)
  • Tencent Captcha Demo (ok)
  • 😉Send Mail same javascript elasticemail (ok)
  • 🥳Các tool phong thuỷ (ok)
  • 😇Nice Select A lightweight Vanilla JavaScript plugin (ok)
  • Merge objects with the same id but sum values of the objects (ok)
  • 😅Page: DOMContentLoaded, load, beforeunload, unload phần 1 (ok)
  • 😍Scripts: async, defer phần 2(ok)
  • 😂Javascript Array chunkArrayInGroups(arr, size)
  • Sequentially Resolve Promises Works, Giải quyết tuần tự các lời hứa hoạt động (ok)
  • Using Async / Await with the Array Reduce Method API (ok)
  • Flatten an array of arrays,merge, làm phẳng một mảng các mảng (ok)
  • 😌Dependent Dropdown Full (ok)
  • 🥳Select Box Change Dependent Options dynamically (JavaScript Object)
  • 🤩Add elements dynamically full (ok)
  • 😅👌Multiple versions jquery (ok)
  • 😍Cách sử dụng jQuery trong sweetAlert2 là chúng ta phải sử dụng didOpen full (ok)
  • 😁😁 mdbgo.io, mdbootstrap.com full (ok)
  • 🤪Chú ý nếu lỗi cảnh báo từ khóa new nếu dùng trong js thường chúng ta sẽ sử dụng trong mudule (ok)
  • 😝reCAPTCHA javascript (ok)
  • Firework Simulator v2 Phao Hoa (ok)
  • Active scroll center (ok)
  • 🤪Sort array of objects by string property value (ok)
  • 😏findIndex, find index in Array object (ok)
  • 😂Sử dụng nhiều toán tử 3, multiple Ternary Operators (ok)
  • 😅A simple and easy to use library that creates fullscreen scrolling websites fullPage.js (ok)
  • Xây dựng ứng dụng CRUD sử dụng Vue.js trong Laravel (ok)
  • [Chart] Morris.js Line & Area Charts,Bar Charts, Donut Charts, graph (ok)
  • [Chart] Chart.js
  • Multi select checkbox table bootstrap (ok)
  • 😀jquery new, jquery old, jquery migrate (ok)
  • Popup slide up from the bottom overflowing other div blocks (ok)
  • ASYNC JavaScript (CALLBACK, PROMISES, ASYNC AWAIT) video (ok)
  • === START jQuery Mobile ===
  • Data Attributes full (ok)
  • Viết một ứng dụng Restaurant Picke sử dụng "back menu" (ok)
  • Viết một ứng dụng thời tiết, Weather sử dụng panel (ok)
  • jQuery Mobile Tutorial w3schools.com (ok)
  • jQuery Mobile
  • jQuery Mobile - Events (ok)
  • Back button in jquery mobile (ok)
  • === END jQuery Mobile ===
  • removeDuplicates, Remove duplicate values from JS array, remove all duplicates an array object (ok)
  • Sử dụng thư viện jquery.hoverdir.js để làm hiệu ứng hover tuyệt đẹp (ok)
  • Modernizr là gì ? Sử dụng nó cho những trình duyệt cũ ra sao? (ok)
  • Nhận biết tính năng CSS: Modernizr hay Feature Queries? (ok)
  • [SALESFORCE] Remote Action function in Visualforce Page (ok)
  • ScrollIt.js menu (ok)
  • Cách sử dụng scrollTo vanilla cực chất 😘 (ok)
  • Một bài toán xử lý bất đồng bộ trong kintone để lấy số requet quá giới hạn (OK)
  • hexagon thư viện tạo avatar Canvas (ok)
  • 😅Sử dụng Object.assign và để copy dữ liệu, edit, input, form (ok)
  • Một cách đặt và gán giá trị trong mảng, object cự ngắn gọn (ok)
  • [LAZY] jQuery.Lazy và tạo background-loading cực chất (ok)
  • Ví dụ Sử dụng sẵn thư viện masonry của wordpres (ok)
  • Ảnh base64 dùng làm src, placeholder (ok)
  • Kiểm tra hình ảnh đã được tải với thư viện imagesLoaded (ok)
  • Check if Function Exists before Calling? (ok)
  • Async/Await Javascript Full Example (ok)
  • Thenables in JavaScript phục vụ cho bài viết trên (ok)
  • Script distance, khoảng cách (ok)
  • Time, Date full (ok)
  • Function getAllDatesOfMonth (ok)
  • How do I make a placeholder for a 'select' box? (ok)
  • Library choise (ok)
  • jQuery - Redirect with post, Get data php (ok)
  • How to pass data from one page to another page html (ok)
  • how to send data onClick() to another php for processing using post or get?
  • draw grid, vẽ grid (ok)
  • Fullscreen Horizontal Page Slider with jQuery and CSS3 - HSlider scroll template html (ok)
  • _.template, UnderscoreJS Templates Full (ok)
  • Character limit on tag type input number (ok)
  • How to set maximum length in input type=number (ok)
  • ========= START JEST =======
  • Getting Started (ok)
  • Using Matchers (ok)
  • Testing Asynchronous Code
  • Setup and Teardown (ok)
  • Mock Functions
  • Jest Platform
  • Jest tutorial
  • Testing trong Javascript với Jest (Phần 1) (ok)
  • Testing trong Javascript với Jest (Phần 2)
  • Giới thiệu về Jest (Delightful JavaScript Testing)
  • Thử nghiệm phát triển theo hướng phản ứng với Jest và Enzyme
  • Cách kiểm tra các thành phần phản ứng với Jest và Enzyme, Phần 1
  • Cách kiểm tra thành phần phản ứng với Jest và Enzyme, Phần 2
  • Jest js mock jquey and lib
  • Unit testing Các thành phần React với Enzyme và Jest
  • Hướng dẫn viết unit test React với Jest và Enzyme (P1)
  • Tôi đã test các React component như thế nào? (phần 2)
  • Test component trong React với Jest
  • Test Component với Jest và Emzyme
  • Tổng quan về unit test cho dự án react redux saga với Jest Part 1
  • ========= END JEST =======
  • ======= START GULP TUTORIAL ======
  • [GULP] Tìm hiểu về Gulp.js
  • [GULP] Gulp Tutorial
  • [GULP] Gulp - Developing An Application (ok)
  • [GULP] Gulp - Combining Tasks (ok)
  • [GULP] Gulp - Watch (ok)
  • [GULP] Gulp - Live Reload
  • [GULP] Gulp - Optimizing CSS and JavaScript
  • [GULP] Gulp - Optimizing Images
  • [GULP] Gulp - Useful Plugins
  • [GULP] Gulp - Cleaning Unwanted Files
  • Đọc thêm những tài liệu trang khác
  • ======= END GULP TUTORIAL ======
  • Prevent form submission on Enter key press, keyCode (ok)
  • Lấy kích thước ảnh gốc image (ok)
  • 😆How to Center Carousel Slider (ok)
  • Putting Dots onto Owl Carousel Instead of below specialtouchgifts.com.au (ok)
  • Cách xây dựng một Full Screen Carousel với Owl.js
  • Lazy load với owl.carousel.js (ok)
  • Show half of the other item on Owl Carousel vinmec.com items: 1.5 (ok)
  • Show half of the other item on Owl Carousel vinmec.com stagePadding (ok)
  • ------------ Start Fetch -----------
  • Using Fetch Full
  • 😅Javascript Fetch JSON PHP Complete FormData phần 1(ok)
  • Một ví dụ quá đỉnh lấy dữ liệu của form submit trong js bằng đối tượng new FormData + php phần 2(ok)
  • Có một sự thật sử dụng async đồng nghĩa với trả về kết quả là PROMISE (ok)
  • 😅Promise.all full (ok)
  • All you need to know about Promise.all
  • [PROMISE] Promise.all()
  • [PROMISE] Tìm hiểu về promise trong ES6
  • [PROMISE] Introduction to Promises
  • jQuery off() Method (ok)
  • How to make HTTP requests with Axios
  • Axios vs Fetch - 2020 nên sử dụng thằng nào với những tính năng mới trong javascript
  • Get and Post method using Fetch API (ok)
  • Sử dụng JavaScript Fetch API với Async/Await (ok)
  • Xử lý lỗi cho fetch trong trường hợp không có kết nối hoặc kết nối lâu (ok)
  • ------------ End Fetch -----------
  • BigDataCloud Free Reverse Geocoding Javascript API Client (ok)
  • Vietmap API
  • 🥰Sử dụng API Giao hàng Nhanh để tính giá cước vận chuyển (ok)
  • photonsearch as you type with OpenStreetMap map (ok)
  • Leaflet - Một thư viện JS mã nguồn mở cho việc xây dụng ứng dụng bản đồ map (ok)
  • Xây dựng popup lấy vị trí map áp dụng pointfinder (ok)
  • Reverse Geocoding Convert Lat Long to Address map (ok)
  • Free Reverse Geocoding Javascript API map (ok)
  • [YAML] In Action Tutorial Series - General - Hướng dẫn sử dụng file YML YAML cơ bản
  • ----------------- Start Notification -----------------
  • Đối tượng caches object caches (ok)
  • Notification (ok)
  • Sử dụng indexedDB (ok)
  • Using the Notifications API (ok)
  • NotificationEvent (chưa có ví dụ :((
  • ServiceWorkerGlobalScope.onnotificationclick (ok)
  • ServiceWorkerRegistration.getNotifications(ok)
  • ServiceWorkerRegistration.showNotification(ok)
  • Giao tiếp giữa các cửa sổ với Window.postMessage API (ok)
  • Window open() Method (ok)
  • ----------------- End Notification -----------------
  • Example Cookie full (ok)
  • Thay đổi class active javascript bằng cách viết hàm (P1)
  • Thay đổi class active javascript bằng cách viết hàm (P2)
  • jQuery Mockjax Plugin (chưa học cách sử dụng)
  • jQuery Ajax X-editable bootstrap plugin (chưa học cách sử dụng)
  • Lọc theo điều kiện (filter) (ok)
  • Các ví dụ về filter
  • jQuery | grep() Method (ok)
  • Hai bài toán so sánh kinh điển trong javascript
  • Function random :)
  • Một cách sử dụng tab trong theme newspaper
  • Hiệu ứng scroll + animation + menu trượt mượt
  • Trigger a CSS animation on scroll xuongkhopbacninh.vn (ok)
  • App Css Loaded (scroll create link) (ok)
  • Hiệu tứng scroll cực chất (ok)
  • App Js Loaded (ok)
  • Sử dụng async và defer full (Oke)
  • Cách sử dụng Thuộc tính async và defer trong JavaScript hay
  • ReferenceError: Can't find variable: requestAnimationFrame
  • Đoạn code check lỗi PHP trong Ajax
  • [SELECT2] Sử dụng Select2 để thay thế select boxes
  • Một cách sử dụng lazyload khi addclass thật khó khăn...
  • Hiệu ứng croll chuột và % cực đẹp :_
  • 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)
  • 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 2)
  • JavaScript String split() Method (OK)
  • Sử dụng thư viện displace để làm menu kéo thả (ok):)))
  • Menu cực chất :)))
  • Sử dụng thư viện slick (ok)
  • vertical scroll, Vertical carousel (ok)
  • Google-like Thanos disintegration (ok)
  • Dùng thư viện jspdf
  • Công thức Toán học cho website
  • Fix lỗi tự động làm thay đổi độ cao :( vieclam123.vn :(
  • Sử dụng window.addEventListener để resize và responsive <3
  • Javascript create, read, and delete cookies (ok)
  • Tự động submit bằng javscript :))) (ok)
  • avoid form warning if user clicks refresh (ok)
  • Một cách truy cập phần tử bằng js thông qua id lạ :)))
  • Meta Refresh
  • Truyền dữ liệu từ javascript sang php
    • Sử dụng form để truyền sang php (ok)
    • Truyền giá trị theo file bằng đường dẫn (ok)
    • Dùng json để truyền sang php
  • auto-refresh page once only after first load – Using JavaScript / JQuery
    • auto-refresh page once only after first load – Using JavaScript / JQuery (ok)
  • Sticky Scroller
    • Sticky Scroller phần 1 (ok)
    • Sticky Scroller phần 2 (ok)
    • owl carousel with dotsContainer (Dots + Text) (ok)
    • Owl Carousel 2 Thumbnails plugin (ok)
  • easy_background Background Slideshow (ok) dev.vieclam123.vn
  • scroll cực chất timviec365.vn, vieclam123.vn (ok)
  • Thư viện lightslider-master gần giống với Owl Carousel
  • Thư viện lightGallery để làm những bộ Sưu tập Gallery
  • Tự viết click slide (ok)
  • Draggable & Touch-friendly Slider Carousel In Pure JS (ok)
  • Slider owl được viết dưới dạng Thumnail (0k)
  • jquery.js:5092 [Violation] Added non-passive event listener to a scroll-blocking 'touchstart' (ok)
  • Added non-passive event listener to a scroll-blocking 'touchstart' event (ok)
  • sticky-mobile-menu-burger-menu (ok)
  • How can I add class to the first and last item among the visible items of Owl Carousel 2? (ok)
  • Owl-carousel2 DEMO - items in 2 rows (oke)
  • How can I create a carousel slick with multiple rows? (ok)
  • Một cách sử dụng create <style> để thêm style (ok)
  • Two Rows Olw Carousel (ok) vieclam123.vn
  • Chức năng tự gọi Javascript (ok) tự động auto
  • Click Next Javascript Base (ok)
  • Slider owl được viết dưới dạng Thumnail viết trên jsfiddle (0k)
  • 😆Creating a Countdown Timer, dakhoathienhoa.com.vn (oK)
  • 🥸NumScroller, Counter From Zero To Value - Javascript Animation (ok)
  • Click Button background-hover white (ok)
  • CodePen HomeLazy Loading Images (Ok)
  • Custom Date Javasript (job247.vn)
  • Tooltip
  • button thay đổi thẻ tags button và span trong Owl Carousel thành thẻ khác :)) (ok)
  • Thêm class vào navigation Owl Carousel (ok)
  • Click lần đầu sử event.preventDefault(); lầu sau not event.preventDefault();
  • landscape && landscape (ok)
  • Landscape && Portrait (ok) job247.vn
  • Hammer thư viện JavaScript chạm cho màn hình cảm ứng
  • jQuery Plugin To Add CSS3 Scrolling Effects On Your Web Page - Smoove menu (ok)
  • 😃Auto Expanding Table Of Contents Plugin - Dynamic Content menu (ok)
  • Tornis - watch and respond
  • scroll-manager
  • Xem thêm
  • Hướng dẫn nấu món "Lazy loading image" theo chuẩn 5 sao Google
  • Welcome to jquery-confirm!
    • jQuery Message Box Plugin Demo Page
  • Magnific-Popup Popup img
  • Slider Swiper Slider-Swiper dùng viết slider giống app
  • Magnific Popup Documentation
  • filter search (ok)
  • Is it possible to convert a select menu to buttons? (ok)
  • Changing selected option on button click select (ok) homef.vn hoặc inop.vyanh.net
  • scrooll animation (job247.vn) (ok)
  • Select2 tutorial
    • Single select boxes (ok)
  • [SELECT2] Disabling a Select2 control (ok)
  • Disabling options (ok)
  • placeholder (ok)
  • Hiển thị nút xóa các giá trị đã chọn + allowClear (ok)
  • Đọc dữ liệu từ một mảng, Data sources (ok)
  • Sử dụng database + php (ok)
  • [SELECT2] Sử dụng form + select2 + ajax + get value (ok)
  • Đọc dữ liệu từ nguồn khác sử dụng AJAX (ok)
  • Thiết lập giá trị mặc định ban đầu trên HTML như bình thường (ok)
  • Sử dụng Ajax để tải dữ liệu từ một nguồn khác (ok)
  • change form
Powered by GitBook
On this page
  • Options: autoFocus
  • Options: appendTo
  • Options: classes
  • Options: delay
  • Options: disabled
  • Options: minLength
  • Options: position
  • Options: source
  • Methods: close()
  • Methods: destroy()
  • Methods: disable()
  • Methods: enable()
  • Methods: instance()
  • Methods: option( optionName )
  • Methods: option()
  • Methods: option( optionName, value )
  • Methods: option( options )
  • Methods: search( [value ] )
  • Methods: widget()
  • Extension Points:
  • Extension Points: _renderItem( ul, item )
  • Extension Points: _renderMenu( ul, items )
  • Extension Points: _resizeMenu()
  • Events: change( event, ui )
  • Events: close( event, ui )
  • Events: create( event, ui )
  • Events: create( event, ui )
  • Events: focus( event, ui )
  • Events: open( event, ui )
  • Events: response( event, ui )
  • Events: search( event, ui )
  • Events: select( event, ui )

Was this helpful?

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 2)

https://api.jqueryui.com/autocomplete/

PreviousTạ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)NextJavaScript String split() Method (OK)

Last updated 4 years ago

Was this helpful?

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

Options: autoFocus

Nếu được đặt thành true, mục đầu tiên sẽ tự động được tập trung khi menu được hiển thị.

<!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>
  <script type='text/javascript'>
  jQuery(document).ready(function($) {
    $(".selector").autocomplete({
      source: function(request, response) {
        $.ajax({
          url: "fetchData.php",
          type: 'post',
          dataType: "json",
          data: {
            search: request.term
          },
          success: function(data) {
            response(data);
          }
        });
      },
      autoFocus: true
    });
  });
  </script>
  <input type='text' class="selector" />
  <div id="someElem"></div>
</body>

</html>

Options: appendTo

<!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>
  <script type='text/javascript'>
  jQuery(document).ready(function($) {
    $(".selector").autocomplete({
      source: function(request, response) {
        $.ajax({
          url: "fetchData.php",
          type: 'post',
          dataType: "json",
          data: {
            search: request.term
          },
          success: function(data) {
            response(data);
          }
        });
      },
      appendTo: "#someElem"
    });
  });
  </script>
  <input type='text' class="selector" />
  <div id="someElem"></div>
</body>

</html>

Options: classes

<!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>
  <script type='text/javascript'>
  jQuery(document).ready(function($) {
    $(".selector").autocomplete({
      source: function(request, response) {
        $.ajax({
          url: "fetchData.php",
          type: 'post',
          dataType: "json",
          data: {
            search: request.term
          },
          success: function(data) {
            response(data);
          }
        });
      },
      classes: {
        "ui-autocomplete": "highlight abc"
      }
    });
  });
  </script>
  <input type='text' class="selector" />
  <div id="someElem"></div>
</body>

</html>

Options: delay

Độ trễ tính bằng mili giây giữa khi tổ hợp phím xảy ra và khi tìm kiếm được thực hiện. Độ trễ bằng không có ý nghĩa đối với dữ liệu cục bộ (phản hồi nhanh hơn), nhưng có thể tạo ra nhiều tải cho dữ liệu từ xa, trong khi ít phản hồi hơn.

$( ".selector" ).autocomplete({
  delay: 500
});

Options: disabled

Vô hiệu hóa tự động hoàn thành nếu được đặt thành đúng.

$( ".selector" ).autocomplete({
  disabled: true
});

Options: minLength

Số lượng ký tự tối thiểu mà người dùng phải nhập trước khi thực hiện tìm kiếm. Không hữu ích cho dữ liệu cục bộ chỉ với một vài mục, nhưng nên sử dụng giá trị cao hơn khi tìm kiếm một ký tự có thể khớp với vài nghìn mục.

$( ".selector" ).autocomplete({
  minLength: 1
});

Options: position

Default: { my: "left top", at: "left bottom", collision: "none" }

Xác định vị trí của menu gợi ý liên quan đến yếu tố đầu vào liên quan. Tùy chọn mặc định cho thành phần đầu vào, nhưng bạn có thể chỉ định một yếu tố khác để định vị. Bạn có thể tham khảo tiện ích Vị trí giao diện người dùng jQuery để biết thêm chi tiết về các tùy chọn khác nhau.

$( ".selector" ).autocomplete({
  position: { my : "right top", at: "right bottom" }
});

Options: source

Xác định dữ liệu để sử dụng, phải được chỉ định. Không phụ thuộc vào biến thể bạn sử dụng, nhãn luôn được coi là văn bản. Nếu bạn muốn nhãn được coi là html, bạn có thể sử dụng phần mở rộng html của Scott González. Tất cả các bản demo tập trung vào các biến thể khác nhau của tùy chọn nguồn - tìm kiếm một biến thể phù hợp với trường hợp sử dụng của bạn và kiểm tra mã.

Multiple types supported:

Array: An array can be used for local data. There are two supported formats:

An array of strings: [ "Choice1", "Choice2" ]
An array of objects with label and value properties: [ { label: "Choice1", value: "value1" }, ... ]

Thuộc tính nhãn được hiển thị trong menu gợi ý. Giá trị sẽ được chèn vào phần tử đầu vào khi người dùng chọn một mục. Nếu chỉ một thuộc tính được chỉ định, nó sẽ được sử dụng cho cả hai, ví dụ: nếu bạn chỉ cung cấp các thuộc tính giá trị, giá trị cũng sẽ được sử dụng làm nhãn

String: Khi một chuỗi được sử dụng, plugin Tự động hoàn thành mong muốn chuỗi đó trỏ đến tài nguyên URL sẽ trả về dữ liệu JSON. Nó có thể trên cùng một máy chủ hoặc trên một máy chủ khác (phải hỗ trợ CORS). Plugin Autocomplete không lọc kết quả, thay vào đó, một chuỗi truy vấn được thêm vào với một trường thuật ngữ, mà tập lệnh phía máy chủ nên sử dụng để lọc kết quả.

Function: Biến thể thứ ba, một cuộc gọi lại, cung cấp sự linh hoạt nhất và có thể được sử dụng để kết nối bất kỳ nguồn dữ liệu nào với Tự động hoàn thành, bao gồm JSONP. Cuộc gọi lại có hai đối số:

A request object, với một thuộc tính thuật ngữ duy nhất, tham chiếu đến giá trị hiện tại trong văn bản nhập. Ví dụ: nếu người dùng nhập "new yo" trong trường thành phố, thuật ngữ Tự động hoàn thành sẽ bằng "new yo".

A response callback, mà mong đợi một đối số duy nhất: dữ liệu để đề xuất cho người dùng. Dữ liệu này phải được lọc dựa trên thuật ngữ được cung cấp và có thể ở bất kỳ định dạng nào được mô tả ở trên đối với dữ liệu cục bộ đơn giản. Điều quan trọng khi cung cấp một cuộc gọi lại nguồn tùy chỉnh để xử lý lỗi trong khi yêu cầu. Bạn phải luôn gọi lại cuộc gọi lại ngay cả khi bạn gặp lỗi. Điều này đảm bảo rằng widget luôn có trạng thái chính xác.

Khi lọc dữ liệu cục bộ, bạn có thể sử dụng hàm $ .ui.autocomplete.escapeRegex tích hợp. Nó sẽ lấy một đối số chuỗi đơn và thoát tất cả các ký tự regex, làm cho kết quả an toàn để chuyển sang RegExp () mới.

Methods: close()

$( ".selector" ).autocomplete( "close" );

Methods: destroy()

Loại bỏ hoàn toàn chức năng tự động hoàn thành. Điều này sẽ đưa phần tử trở lại trạng thái trước khi khởi tạo.

$( ".selector" ).autocomplete( "destroy" );

Methods: disable()

$( ".selector" ).autocomplete( "disable" );

Methods: enable()

$( ".selector" ).autocomplete( "enable" );

Methods: instance()

Lấy đối tượng cá thể tự động hoàn thành. Nếu phần tử không có phiên bản liên quan, không xác định được trả về.

Không giống như các phương thức widget khác, instance () an toàn để gọi bất kỳ phần tử nào sau khi plugin tự động hoàn tất đã được tải.

$( ".selector" ).autocomplete( "instance" );

Methods: option( optionName )

Nhận giá trị hiện được liên kết với tùy chọn Tên được chỉ định.

Lưu ý: Đối với các tùy chọn có các đối tượng là giá trị của chúng, bạn có thể nhận giá trị của một khóa cụ thể bằng cách sử dụng ký hiệu dấu chấm. Ví dụ: "foo.bar" sẽ nhận giá trị của thuộc tính thanh trên tùy chọn foo.

var isDisabled = $( ".selector" ).autocomplete( "option", "disabled" );

Methods: option()

Nhận một đối tượng chứa các cặp khóa / giá trị đại diện cho hàm băm tùy chọn tự động hoàn thành hiện tại.

var options = $( ".selector" ).autocomplete( "option" );

Methods: option( optionName, value )

Đặt giá trị của tùy chọn tự động hoàn thành được liên kết với tùy chọn Tên được chỉ định.

Lưu ý: Đối với các tùy chọn có các đối tượng là giá trị của chúng, bạn có thể đặt giá trị của chỉ một thuộc tính bằng cách sử dụng ký hiệu dấu chấm cho tùy chọn Tên. Ví dụ: "foo.bar" sẽ chỉ cập nhật thuộc tính thanh của tùy chọn foo.

optionName: The name of the option to set.
value: A value to set for the option
$( ".selector" ).autocomplete( "option", "disabled", true );

Methods: option( options )

Sets one or more options for the autocomplete.

$( ".selector" ).autocomplete( "option", { disabled: true } );

Methods: search( [value ] )

Kích hoạt một sự kiện tìm kiếm và gọi nguồn dữ liệu nếu sự kiện không bị hủy. Có thể được sử dụng bởi một nút giống như hộp chọn để mở các đề xuất khi nhấp vào. Khi được gọi không có tham số, giá trị của đầu vào hiện tại được sử dụng. Có thể được gọi với một chuỗi rỗng và minLpm: 0 để hiển thị tất cả các mục.

$( ".selector" ).autocomplete( "search", "" );

Methods: widget()

Trả về một đối tượng jQuery chứa thành phần menu. Mặc dù các mục menu liên tục được tạo và hủy, phần tử menu được tạo trong quá trình khởi tạo và liên tục được sử dụng lại.

$( ".selector" ).autocomplete( "widget" );

Extension Points:

Tiện ích tự động hoàn thành được xây dựng cùng với nhà máy phụ tùng và có thể được mở rộng. Khi mở rộng các widget, bạn có khả năng ghi đè hoặc thêm vào hành vi của các phương thức hiện có. Các phương thức sau được cung cấp dưới dạng các điểm mở rộng có độ ổn định API giống như các phương thức plugin được liệt kê ở trên. Để biết thêm thông tin về tiện ích mở rộng tiện ích, hãy xem Mở rộng tiện ích với Nhà máy tiện ích.

Extension Points: _renderItem( ul, item )

Phương pháp kiểm soát việc tạo từng tùy chọn trong menu của widget. Phương thức phải tạo một phần tử mới, nối nó vào menu và trả lại nó. Xem tài liệu Menu để biết thêm chi tiết về đánh dấu

ul
The <ul> element that the newly created <li> element must be appended to.
item: 
    label (Type: String)
    value (Type: String)
The value to insert into the input when the item is selected.
_renderItem: function( ul, item ) {
  return $( "<li>" )
    .attr( "data-value", item.value )
    .append( item.label )
    .appendTo( ul );
}

Extension Points: _renderMenu( ul, items )

Phương pháp kiểm soát việc xây dựng menu của widget. Phương thức này được thông qua một trống và một mảng các mục khớp với thuật ngữ người dùng đã nhập. Việc tạo các phần tử riêng lẻ phải được ủy quyền cho _renderItemData (), lần lượt ủy nhiệm cho điểm mở rộng _renderItem ().

ul
Type: jQuery
An empty <ul> element to use as the widget's menu.
items
Type: Array
An Array of items that match the user typed term. Each item is an Object with label and value properties.
_renderMenu: function( ul, items ) {
  var that = this;
  $.each( items, function( index, item ) {
    that._renderItemData( ul, item );
  });
  $( ul ).find( "li:odd" ).addClass( "odd" );
}

Extension Points: _resizeMenu()

Phương pháp chịu trách nhiệm định cỡ menu trước khi nó được hiển thị. Phần tử menu có sẵn tại this.menu.element

_resizeMenu: function() {
  this.menu.element.outerWidth( 500 );
}

Events: change( event, ui )

Kích hoạt khi trường bị mờ, nếu giá trị đã thay đổi.

event
Type: Event
ui
Type: Object
item
Type: Object
The item selected from the menu, if any. Otherwise the property is null.
Các mục được chọn từ menu, nếu có. Nếu không tài sản là null.
$( ".selector" ).autocomplete({
  change: function( event, ui ) {}
});
Bind an event listener to the autocompletechange event:
$( ".selector" ).on( "autocompletechange", function( event, ui ) {} );

Events: close( event, ui )

Triggered when the menu is hidden. Not every close event will be accompanied by a change event.

Kích hoạt khi menu bị ẩn. Không phải mọi sự kiện gần gũi sẽ được đi kèm với một sự kiện thay đổi.

Lưu ý: Đối tượng ui trống nhưng được bao gồm để thống nhất với các sự kiện khác.

$( ".selector" ).autocomplete({
  close: function( event, ui ) {}
});

Bind an event listener to the autocompleteclose event:

$( ".selector" ).on( "autocompleteclose", function( event, ui ) {} );

Events: create( event, ui )

Lưu ý: Đối tượng ui trống nhưng được bao gồm để thống nhất với các sự kiện khác.

$( ".selector" ).autocomplete({
  create: function( event, ui ) {}
});

Bind an event listener to the autocompletecreate event:

$( ".selector" ).on( "autocompletecreate", function( event, ui ) {} );

Events: create( event, ui )

Kích hoạt khi tự động hoàn thành được tạo.

Lưu ý: Đối tượng ui trống nhưng được bao gồm để thống nhất với các sự kiện khác.

$( ".selector" ).autocomplete({
  create: function( event, ui ) {}
});

Bind an event listener to the autocompletecreate event:

	$( ".selector" ).on( "autocompletecreate", function( event, ui ) {} );

Events: focus( event, ui )

Kích hoạt khi tiêu điểm được chuyển đến một mục (không chọn). Hành động mặc định là thay thế giá trị của trường văn bản bằng giá trị của mục được tập trung, mặc dù chỉ khi sự kiện được kích hoạt bởi tương tác bàn phím. Hủy bỏ sự kiện này sẽ ngăn giá trị được cập nhật, nhưng không ngăn mục menu bị tập trung.

$( ".selector" ).autocomplete({  focus: function( event, ui ) {}});

Bind an event listener to the autocompletefocus event:

$( ".selector" ).on( "autocompletefocus", function( event, ui ) {} );

Events: open( event, ui )

Kích hoạt khi menu gợi ý được mở hoặc cập nhật.

Initialize the autocomplete with the open callback specified:

$( ".selector" ).autocomplete({
  open: function( event, ui ) {}
});

Bind an event listener to the autocompleteopen event:

$( ".selector" ).on( "autocompleteopen", function( event, ui ) {} );

Events: response( event, ui )

Kích hoạt sau khi tìm kiếm hoàn thành, trước khi menu được hiển thị. Hữu ích cho thao tác cục bộ của dữ liệu đề xuất, trong đó không yêu cầu gọi lại tùy chọn nguồn tùy chỉnh. Sự kiện này luôn được kích hoạt khi tìm kiếm hoàn tất, ngay cả khi menu sẽ không được hiển thị vì không có kết quả hoặc Tự động hoàn tất bị tắt.

event
Type: Event
ui
Type: Object
Chứa dữ liệu phản hồi và có thể được sửa đổi để thay đổi kết quả sẽ được hiển thị. Dữ liệu này đã được chuẩn hóa, vì vậy nếu bạn sửa đổi dữ liệu, hãy đảm bảo bao gồm cả thuộc tính giá trị và nhãn cho từng mục.

Initialize the autocomplete with the response callback specified:

$( ".selector" ).autocomplete({  response: function( event, ui ) {}});

Bind an event listener to the autocompleteresponse event:

$( ".selector" ).on( "autocompleteresponse", function( event, ui ) {} );

Events: search( event, ui )

Kích hoạt trước khi tìm kiếm được thực hiện, sau khi độ dài và độ trễ được đáp ứng. Nếu hủy bỏ, sau đó không có yêu cầu sẽ được bắt đầu và không có mục nào được đề xuất.

Initialize the autocomplete with the search callback specified:

$( ".selector" ).autocomplete({
  search: function( event, ui ) {}
});

Bind an event listener to the autocompletesearch event:

$( ".selector" ).on( "autocompletesearch", function( event, ui ) {} );

Events: select( event, ui )

Kích hoạt khi một mục được chọn từ menu. Hành động mặc định là thay thế giá trị của trường văn bản bằng giá trị của mục được chọn. Hủy bỏ sự kiện này ngăn giá trị được cập nhật, nhưng không ngăn menu đóng.

event
Type: Event
ui
Type: Object
item
Type: Object
An Object with label and value properties for the selected option.

Initialize the autocomplete with the select callback specified:

$( ".selector" ).autocomplete({
  select: function( event, ui ) {}
});

Bind an event listener to the autocompleteselect event:

$( ".selector" ).on( "autocompleteselect", function( event, ui ) {} );

Ví dụ 1:

Using a custom source callback to match only the beginning of terms
Sử dụng một cuộc gọi lại nguồn tùy chỉnh để chỉ khớp với phần đầu của các điều khoản
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>autocomplete demo</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
  <script src="//code.jquery.com/jquery-1.12.4.js"></script>
  <script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
 
<label for="autocomplete">Select a programming language: </label>
<input id="autocomplete">
 
<script>
var tags = [ "c++", "java", "php", "coldfusion", "javascript", "asp", "ruby" ];
$( "#autocomplete" ).autocomplete({
  source: function( request, response ) {
          var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( request.term ), "i" );
          response( $.grep( tags, function( item ){
              return matcher.test( item );
          }) );
      }
});
</script>
 
</body>
</html>

Ví dụ 2:

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>
  <div class="ui-widget">
    <label for="birds">Birds: </label>
    <input id="birds">
  </div>
  <div class="ui-widget" style="margin-top:2em; font-family:Arial">
    Result:
    <div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
  </div>
  <script>
  jQuery(document).ready(function($) {
    $(function() {
      function log(message) {
        $("<div>").text(message).prependTo("#log");
        $("#log").scrollTop(0);
      }
      $("#birds").autocomplete({
        source: function(request, response) {
          $.ajax({
            url: "search.php",
            dataType: "json",
            data: {
              term: request.term
            },
            success: function(data) {
              response(data);
            }
          });
        },
        minLength: 2,
        select: function(event, ui) {
          log("Selected: " + ui.item.value + " aka " + ui.item.id);
        }
      });
    });
  });
  </script>
</body>

</html>

search.php

<?php
$arr = array(
  [
    "id"=>"Branta canadensis",
    "label"=>"Greater Canada Goose",
    "value"=>"Greater Canada Goose",
  ],
  [
    "id"=>"Chlamydotis undulata",
    "label"=>"Houbara Bustard",
    "value"=>"Houbara Bustard",
  ],
  [
    "id"=>"Anser fabalis",
    "label"=>"Taiga Bean Goose",
    "value"=>"Taiga Bean Goose",
  ],
  [
    "id"=>"Anser serrirostris",
    "label"=>"Tundra Bean Goose",
    "value"=>"Tundra Bean Goose",
  ],
  [
    "id"=>"Anthus gustavi",
    "label"=>"Pechora Pipit",
    "value"=>"Pechora Pipit",
  ],
  [
    "id"=>"Branta hutchinsii",
    "label"=>"Lesser Canada Goose",
    "value"=>"Lesser Canada Goose",
  ],
  [
    "id"=>"Melanocorypha calandra",
    "label"=>"Calandra Lark",
    "value"=>"Calandra Lark",
  ],
  [
    "id"=>"Puffinus baroli",
    "label"=>"Madeira Little Shearwater",
    "value"=>"Madeira Little Shearwater",
  ]
);
echo json_encode($arr);
?>

Ví dụ: nếu tùy chọn nguồn được đặt thành "" và người dùng nhập foo, yêu cầu GET sẽ được gửi tới . Dữ liệu có thể có cùng định dạng với dữ liệu cục bộ được mô tả ở trên.

Closes the Autocomplete menu. Useful in combination with the method, to close the open menu.

http://example.com
http://example.com?term=foo
search
https://config.phpconfig.php
https://fetchData.phpfetchdata.php