首页 > 解决方案 > jquery自动完成搜索输入

问题描述

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css"> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> 
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script> 
... 
<div id="search">
      <form method="get" action="{% url 'main:home' %}">        
        <input type="text" name="q" placeholder="Поиск по сайту" value="{{ request.GET.q }}"> 
        <input id="input_id" type="submit" value="Найти">                 
      </form>
</div>
... 
<script> 
$('#search input[name="q"]').autocomplete({ 
  'source': '{% url "main:home" %}', 
  'minLength': 2, 
//  'appendTo': "#input:last"   
}); 
</script>

如果我按下自动完成,自动完成会删除以前的输入值 图像 ,以前的值会消失。我尝试在注释掉的版本中添加行尾,但这不起作用。需要替换最后一个未完成的单词

标签: javascriptjqueryhtmlajax

解决方案


$('#search input[name="q"]').autocomplete({ 
  'source': '{% url "main:home" %}', 
  'minLength': 2,    
  'appendTo': "#search"   
}).on( "autocompleteselect", function(event, ui) {
  event.preventDefault();
  var words = this.value.split(' ');
  words[words.length - 1] = ui.item.value;
  this.value = words.join(' ');
});

推荐阅读