我正在使用实现CSS的autocomplete功能。
我能够从输入字段触发服务器调用并获取JSON数据并能够显示结果。但是我无法通过选择自动完成项来触发事件。
我的用户输入代码:
<input placeholder="Search ..." class="autocomplete" type="text" (keyup)="onKey($event)">
onKey()获取服务器数据并显示结果,如下所示:
我面临的问题是在选择任何下拉值以获得所选值时
答案 0 :(得分:2)
提供onselect处理程序作为options对象的属性onAutocomplete
。
const options = {
data: {
"All": null,
"Apple": "https://upload.wikimedia.org/wikipedia/commons/f/fa/Apple_logo_black.svg",
"Google": "https://upload.wikimedia.org/wikipedia/commons/5/53/Google_%22G%22_Logo.svg",
"Microsoft": null
},
onAutocomplete: displayResult('autocompleted as')
}
const input = document.querySelector('.autocomplete');
const instances = M.Autocomplete.init(input, options);
const resultContainer = document.querySelector('.result')
function displayResult(state) {
return function(text) {
resultContainer.innerText = "Input " + state + " " + text
}
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.2/css/materialize.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.2/js/materialize.min.js"></script>
<p class="result">Nothing selected in input</p><br>
<div class="input-field col s12">
<input type="text" id="autocomplete-input" class="autocomplete" onchange="displayResult('changed to')(this.value)">
<label for="autocomplete-input">Autocomplete</label>
</div>
答案 1 :(得分:1)
您是否尝试过以这种方式添加onAutocomplete函数
$('input.autocomplete').autocomplete({
data: {
"Apple": null,
"Microsoft": null,
"Google": 'https://placehold.it/250x250'
},
onAutocomplete: function(val) {
console.log(val);
}
});