Home > Back-end >  Is it possible to capture the key associated with a datalist item upon selecting an item from the li
Is it possible to capture the key associated with a datalist item upon selecting an item from the li

Time:12-24

I have the below code to populate a search box with datalist items. The key of the datalist items is set to u.userID and the display is set to u.name. When an item is selected, I can get the u.name which is displayed. How can I get the underlying key associated with the item?

<div >
    <div >
        <input type="search" id="usersearch" list="userList"  placeholder="Search user" 
              @keydown.enter="addUser(selectedUser)" v-model="selectedUser" v-on:input="changingUser($event)" />
        <div >
            <span  id="basic-addon2"> <b-icon icon="search"></b-icon></span>
        </div>
    </div>
    <datalist id="userList">
        <option v-for="u in users" :key="u.userID">{{ u.name }}</option>
    </datalist>
</div>
 methods: {
        addUser(user) {
            console.log(user);
        },
        changingUser(e) {
            if (!e.inputType) {
                this.addUser(this.selectedUser);
            }
        }
    }

CodePudding user response:

It's not possible to get the key from the selected datalist.option because the input-event does not link to the <option> in any way.

While not ideal, you could lookup the user by name, and access the userID:

export default {
  methods: {
    addUser(username) {
      const user = this.users.find(u => u.name === username)
      console.log('addUser ID', { userID: user?.userID })
    },
  }
}

demo

  • Related