In this tutorial we will see how to implement autocomplete on form fields using jQuery UI in ExpressJS.
jQuery UI expects server-side code to return a JSON array of objects having the value
and label
properties.
The first is the real value to be associated with the result (for example an ID) while the second is the text to be displayed in the drop-down menu.
In Node.js we can simply query with the $regex
operator in MongoDB and return the results in the desired format.
'use strict';
const express = require('express');
const router = express.Router();
const Product = require('../models/product');
router.get('/', (req, res, next) => {
res.render('index');
});
router.get('/autocomplete', async (req, res, next) => {
const s = req.query.s.trim();
const results = [];
try {
const products = await Product.find({ title: { $regex: s, $options: 'i' } } ).limit(10);
products.forEach(product => {
let { id, title } = product;
results.push({ value: id, label: title });
});
} catch(err) {
console.log(err);
}
res.json(results);
});
module.exports = router;
The s
parameter is the search term sent by the form. With jQuery UI we must now write the following code.
"use strict";
$(function() {
$( "#s" ).autocomplete({
source: function ( request, response ) {
$.ajax({
url: "/autocomplete",
type: 'GET',
dataType: "json",
data: {
s: request.term
},
success: function ( data ) {
response( data );
}
});
},
select: function ( event, ui ) {
$( "#s" ).val( ui.item.label );
return false;
}
});
});
The select
event allows us to insert the text selected from the drop-down menu into the corresponding form field. In this callback we also have access to the value
property using the ui.item.value
syntax.