Example of Jquery code Example with Autocomplete code Highlighting
With this code snippet you can create an autocomplete Jquery box that highlights the code when there is at least a match among your entries.
- You need to reference jquery, and jquery-ui libraries
Example with Jquery 1.6
Link your html <head></head>
<script src="js/jquery-1.6.min.js" type="text/javascript"></script>
<script src="js/jqueryui/jquery-ui.min.js" type="text/javascript"></script>
Copy the code example:
<div id="search"> <div class="searchfield"> <input type="text" id="s" name="busca"> </div> <div class="searchbtn"> <input type="image" alt="search"> </div> </div> <br/><br/> <input id="url" type="hidden"/> <script> var data =[ {'label':'MySQL - Quick MySQL commands and exaples plus JDBC and JSP examples' ,'value':'quick-mysql-commands-examples'}, {'label':'Maven - How to use maven just to copy dependencies' ,'value':'maven-just-copy-dependencies'}, {'label':'Java - CommunicationsException with Java and MYSQL' ,'value':'communications-exception-java-mariadb-mysql'}, {'label':'Java - Basic Example of Persistence with Java' ,'value':'java-persistence-serializable-example'}, {'label':'Linux - How to find a string in files in linux Ubuntu' ,'value':'ubuntu-find-string-files-example'}, {'label':'Java - Mini Java Socket Server example' ,'value':'java-socket-mini-server-http-example'}, {'label':'Linux - Top 5 linux console applications for me' ,'value':'linux-top-console-applications'}, {'label':'Tomcat - Tomcat disable session persistence' ,'value':'tomcat-disable-session-persistence'}, {'label':'Tomcat - Set Tomcat session Timeout' ,'value':'tomcat-set-session-timeout'}, {'label':'Tomcat - Tomcat How to Set a folder in our app outside the WAR deployment ' ,'value':'tomcat-folder-outside-deploy'}, ]; $.ui.autocomplete.prototype._renderItem = function( ul, item){ var term = this.term.split(' ').join('|'); var re = new RegExp("(" + term + ")", "gi") ; var t = item.label.replace(re,"<strong>$1</strong>"); return $( "<li></li>" ) .data( "item.autocomplete", item ) .append( "<a>" + t + "</a>" ) .appendTo( ul ); }; $("#s").autocomplete({ source:data, minLength: 1, select: function(e, ui) { e.preventDefault(); // <--- Prevent the value from being inserted. $("#url").val(ui.item.value); var redirect = $("#url").val(); window.location.href = redirect; } }); </script>
- change your source:data if needed.
- change the minLength to set the amount of minimun characters typed to start filtering results.
- remove the two last lines var redirect... and window.location.href... if you don't need a redirection after choosing a result.
go to http://www.jcgonzalez.com/home to see a working example