Access Original List Item?
See original GitHub issueI’m having trouble figuring out if I can access the original list item. My goal is to set a data-attribute on the generated list item so I can access the value when the item is selected. The stored value is important to a function call I want to make when something is selected.
My data list looks something like this:
<ul id="myList">
<li data-thing="value">Thing1</li>
<li data-thing="value">Thing2</li>
<li data-thing="value">Thing3</li>
</ul>
And I initialize Awesomplete like this:
var input = document.getElementById("myInput");
var ac = new Awesomplete(input, {
list: "#myList",
minChars: 1,
item: function(text, input) {
// I want to set a data-attribute on the generated item
// by reading a data-attribute from the original list item
}
});
I cannot figure out how to access the original list item to do so. Am I on the right track here, or is there a better way to go about this?
Edit: I noticed in the documentation that the data function has two parameters, item and text, where item is the original list item. I tried testing this with a console log like so:
data: function(item, input) {
console.log(item);
}
But what is logged is just an object with a label and value. I thought that “original list item” meant a reference to the element, so I tried item.getAttribute('data-thing')
but getAttribute is undefined. Am I misunderstanding something?
Issue Analytics
- State:
- Created 7 years ago
- Comments:7
Found my problem. I had another variable “item” in scope that was being accessed rather than what I thought was the list item.
However, I think I just answered my own question. In the
item
function, the first parameter is not just the text as the documentation describes, but is actually the list item. I found this out by console loggingtext
, and found that it was actually my objects from my list.So with Awesomplete initialized like this, I’ve achieved what I was after:
Perhaps the documentation just needs a bit of clarifying?
I’m not quite sure what you’re suggesting, @Ruff9, but what I ended up doing is a bit of a hack…
I was able to initialize my list as an array instead of using HTML. It’s an array of objects in this format:
I then create my Awesomplete list like this:
What ends up happening is the
data-thing
attribute has the value I want, but the text that is displayed in the input is the label. I can then read the data attribute during theawesomplete-select
event like this:If there’s a more direct way of just accessing the original list item in HTML then I’d prefer to do it that way because my current solution feels a bit convoluted. I’m also not entirely certain why it works because I’m not totally clear on when the
data
anditem
functions apply.