Search Form Autocomplete
Previous article Next articleWebsite visitors can quickly find and select from a pre-populated list of values as they type, leveraging searching and filtering.
Based on the jQuery Autocomplete plugin. More documentation at Autocomplete | jQuery.
How to use
1. Search Form Template
Create in Design Manager a new Search Form template and name it "SearchAutocomplete".
In the default content change the ID's for the label and the text input field "{$search_actionid}searchinput" to "autocomplete" or "autocomplete_initial".
The content will now look like:
<label for="autocomplete">{$searchprompt}: </label><input type="text" class="search-input" id="autocomplete" name="{$search_actionid}searchinput" size="20" maxlength="50" placeholder="{$searchtext}"/>
{*
<br/>
<input type="checkbox" name="{$search_actionid}use_or" value="1"/>
*}
<input class="search-button" name="submit" value="{$submittext}" type="submit" />
{if isset($hidden)}{$hidden}{/if}
{$endform}
2. User Defined Tag to read the database
In the Admin Area you go to Extensions >> User Defined Tags.
Create a new UDT, named "SearchAutocomplete" and the content is:
* https://cmscanbesimple.org/blog/search-form-autocomplete
* https://demo.cmscanbesimple.org/search-form-autocomplete
* https://jqueryui.com/autocomplete/
*/
$db = cmsms()->GetDb();
$query = "SELECT DISTINCT `word` FROM " . cms_db_prefix() . "module_search_index ORDER BY `word`";
$result = $db->GetCol( $query );
if ( count($result) )
{
$output = '<script>
window.onload = function() {
var tags = ' . json_encode($result) . ';
// 1. search within words
$( "#autocomplete" ).autocomplete( {
minLength: 0,
source: tags
} );
// 2. search from the initial of the words
$( "#autocomplete_initial" ).autocomplete( {
minLength: 0,
source: function( request, response ) {
var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( request.term ), "i" );
response( $.grep( tags, function( item ) {
return matcher.test( item );
} ) );
}
} );
};
</script>';
echo $output;
}
3. jQuery User Interface
This method uses the jQuery UI Autocomplete library.
Add to your template <head></head> area:
And add this to the bottom of your Core::Page template.
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
{SearchAutocomplete}
Note, maybe other modules also use these. Don't add them twice, it will break the functioning of your website.
4. Search module
Now you can add the Search module tag to your Core::Page template or a page.
Working example
Comment Form
ReviewManager
ReviewManager
0 Comments
No comments yet...