问题
I am using the same Materialize Autocomplete on 3 input elements. Then on onAutocomplete() I need to get the ID of the element the autocomplete was used on so I can populate data in the right place. So I want to know if it was either autocomplete-input1
or autocomplete-input2
. How can I do that in pure javascript?
<div class="col s12">
<div class="row">
<div class="input-field col s6">
<input type="text" id="autocomplete-input1" class="autocomplete" autocomplete="off">
<label for="autocomplete-input1">Input1: Type my name - Radek</label>
</div>
<div class="input-field col s6">
<input type="text" id="autocomplete-input2" class="autocomplete" autocomplete="off">
<label for="autocomplete-input2">Input2: Type my name - Radek</label>
</div>
</div>
</div>
I want to know the ID of element user typed something and use the autocomplete. The javascript code would be part of the onAutocomplete function. I tried few options but none worked.
$(function () {
$('input.autocomplete').autocomplete({
data: {
"Radek Surname <br> radeksurname@ymail.com": null,
"Radek": null,
"Radoslav": 'http://placehold.it/250x250'
},
onAutocomplete: function(txt) {
console.log(this.getAttribute("id"));
console.log(this.id);
console.log(this.innerHTML);
console.log(this.innerText);
console.log(this.outerHTML);
},
limit: 20,
});
});
You can use this jsFiddle and fiddle around ..
回答1:
Example 1 - JsFiddle
$(function () {
const selector = 'input.autocomplete';
let currentActiveAutoCompleteInput = null;
document.querySelectorAll(selector).forEach(el => {
el.onchange = function(evt) {
currentActiveAutoCompleteInput = evt.target;
};
});
$(selector).autocomplete({
data: {
"Radek Surname <br> radeksurname@ymail.com": null,
"Radek": null,
"Radoslav": 'http://placehold.it/250x250'
},
onAutocomplete: function(txt) {
console.log(currentActiveAutoCompleteInput.id);
},
limit: 20,
});
});
Example 2 - JsFiddle
$(function () {
let currentActiveAutoCompleteInput = null;
$('input.autocomplete')
.on('change', function(evt) {
currentActiveAutoCompleteInput = evt.target;
})
.autocomplete({
data: {
"Radek Surname <br> radeksurname@ymail.com": null,
"Radek": null,
"Radoslav": 'http://placehold.it/250x250'
},
onAutocomplete: function(txt) {
console.log(currentActiveAutoCompleteInput.id);
},
limit: 20,
});
});
来源:https://stackoverflow.com/questions/65674742/how-to-get-element-attributes-onautocomplete-with-materialize