• About
  • Programming
  • Contact
  • EN
    • EN
    • ET
  • Snippets

HTML textfield & Javascript autocomplete

07.09.2019 / mast / 0 Comments

The HTML

 

Add author
Delete: right-click author field

PHP file that does the search

Source of suggest_author.php :


if (strlen($_REQUEST['q']) <= 0) exit;

$authors = array(0 => 'John Digweed', 1 => 'Pamela Alemap', 7 => 'Kevin Constner', 8 => 'Abraham Lincoln');

$matches  = preg_grep('/'.$_REQUEST['q'].'/i', $authors);

foreach ((array)$matches as $id => $name) { 
        $output .= "$id|$namen";
} 

if ($output == '') {
        echo 'Not found';
} else {
        echo $output;
}

Javascript

  • Include jQuery
  • Include modified jquery.autocomplete.js
  • Include initiating Javascript:
jQuery(document).ready(function(){
    jQuery(".author").autocomplete("/snippets/autocomplete/suggest_author.php", {assignToName:'authors[]', minChars:1, matchSubset:0, matchContains:0, cacheLength:10, onItemSelect:selectItem, formatItem:formatItem, selectOnly:1 });
});
jQuery('.author').on('contextmenu', function (e) {
    e.preventDefault();
    if (confirm('Remove author '+jQuery(this).val()+'?')) {
      jQuery(this).remove();
    }
});
function addAuthor(where) {
    var el = jQuery('');
    jQuery(where).append(el);
    el.autocomplete("/snippets/autocomplete/suggest_author.php", {assignToName:'authors[]', minChars:1, matchSubset:0, matchContains:0, cacheLength:10, onItemSelect:selectItem, formatItem:formatItem, selectOnly:1 });
    el.on('contextmenu', function (e) {
        e.preventDefault();
        if (confirm('Remove author '+jQuery(this).val()+'?')) {
          jQuery(this).remove();
        }
    });
    el.focus();
}

Include CSS

Include jquery.autocomplete.css

Complete demo for download

Download .zip file

Lightweight HTML/PHP parser »

© Webwise