简体   繁体   中英

Enable autocomplete dropdown when clicked on the contenteditable area

There is an contenteditable span tag with some data. When I edit the data existing inside the span tag i need to clear complete data and then I get the suggestion from autocomplete list. What I need is, I want to display data when a user clicks on span tag with out editing any pre-existing data. Please help me out. Thank you in advance.

This is a very simple example based on http://jqueryui.com/autocomplete/#multiple

 $(function() { var availableTags = [ "ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++", "Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran", "Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl", "PHP", "Python", "Ruby", "Scala", "Scheme" ]; function split(val) { return val.split(" "); } function extractLast(term) { return split(term).pop(); } function moveCursorToEnd(el) { if (typeof el.selectionStart == "number") { el.selectionStart = el.selectionEnd = el.value.length; } else if (typeof el.createTextRange != "undefined") { el.focus(); var range = el.createTextRange(); range.collapse(false); range.select(); } } $("#content") // don't navigate away from the field on tab when selecting an item .on("keydown", function(event) { if (event.keyCode === $.ui.keyCode.TAB && $(this).autocomplete("instance").menu.active) { event.preventDefault(); } }) .autocomplete({ minLength: 0, source: function(request, response) { // delegate back to autocomplete, but extract the last term response($.ui.autocomplete.filter( availableTags, extractLast(request.term))); }, focus: function() { // prevent value inserted on focus return false; }, select: function(event, ui) { var val = $(this).html(); var terms = split(val); // remove the current input terms.pop(); // add the selected item terms.push(ui.item.value); // add placeholder to get the comma-and-space at the end terms.push(""); $(this).html(terms.join(" ")); moveCursorToEnd($(this)[0]); return false; } }); }); 
 #content { min-width: 1em; min-height: 1em; border: 1px solid #eee; border-radius: 3px; padding-left: 1px; } 
 <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <div class="ui-widget"> <label for="content">Edit content: </label> <span id="content" contenteditable="true">Basic</span> </div> 

As you can see, it's been modified to split and join with " " (space) instead of ", ". Assuming you are creating sentences or a list of words, this will work pretty well.

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM