问题
I am using autocomplete feature of materialize css.
I am able to trigger a server call from the input field and getting the JSON data and able to display the result. But I am not able to trigger event by onselect of the autocomplete item.
My code for user input:
<input placeholder="Search ..." class="autocomplete" type="text" (keyup)="onKey($event)">
The onKey() getting the server data and displaying the result as below:
The problem i am facing is while on select of any drop down value to get the selected value
回答1:
Provide your onselect handler as the property onAutocomplete
of the options object.
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>
回答2:
have you tried by adding onAutocomplete function in this way
$('input.autocomplete').autocomplete({
data: {
"Apple": null,
"Microsoft": null,
"Google": 'https://placehold.it/250x250'
},
onAutocomplete: function(val) {
console.log(val);
}
});
来源:https://stackoverflow.com/questions/51458090/how-can-i-trigger-an-event-by-onselect-of-autocomplete-element-of-materialize-cs