Tony Tony - 2 months ago 12
Javascript Question

JavaScript emptying the input after autocomplete select

I have this code which is working fine, but I want to empty the input $project
after the user select an autocomplete suggestion..

$project.autocomplete({
minLength: 1,
source: projects,
focus: function( event, ui ) {
$project.val(ui.item.label);
return false;
},
select: function (e, ui) {
createTag(ui.item.label, ui.item.id);
}
});


where to place this code in order to perform the action after the autocomplete is triggered ?

//document.getElementById("project").value = "";

Answer

You need to use close event:

var projects = [
  "ActionScript",
  "AppleScript",
  "Asp",
  "BASIC",
  "C",
  "C++",
  "Clojure",
  "COBOL",
  "ColdFusion",
  "Erlang",
  "Fortran",
  "Groovy",
  "Haskell",
  "Java",
  "JavaScript",
  "Lisp",
  "Perl",
  "PHP",
  "Python",
  "Ruby",
  "Scala",
  "Scheme"
];

var $project = $( "#tags" );
$project.autocomplete({
  minLength: 1,
  source: projects,
  focus: function( event, ui ) {
    $project.val(ui.item.label);
    return false;
  },
  close: function (e, ui) {
    e.target.value = '';
    //createTag(ui.item.label, ui.item.id);
  }
});
<link href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>

<div class="ui-widget">
    <label for="tags">Tags: </label>
    <input id="tags">
</div>

Comments