Skip to content Skip to sidebar Skip to footer

Get Id Of Selected Item In Datalist

I am having an input element and a datalist for suggestions. I am feeding the an array of object to datalist for suggestions which looks like this [ { 'id': '9cb98eab-7

Solution 1:

Pass the selected item as complete object. Not just the name. Only display the name. In your code you only return the name. But you could return the item or the item.id. The value should be the item. You can still display the name of the item. But passed the object for handling.

Like (Pseudo code):

<option value=item>{item.name}</option>

Or only the id:

<option value={item.id}>{item.name}</option>

Maybe you have to adjust a bit to conform with your code. but the main message is, that you can set a tag value and pass the item as object as option value.

<option value={what-ever-you-want}>{what-the-user-will-see}</option>

Working native HTML example:

<select onchange="console.log(this.value)">
  <option value="id-1">Name 1</option>
  <option value="id-2">Name 2</option>
  <option value="id-3">Name 3</option>
  <option value="id-4">Name 4</option>
</select>

Will print the id of the selected item in console of the browser. (Press F12 or Ctrl + Shift + i to show the console)


Solution 2:

You could put the id from the array as a value in the JSX.

<option value= {item.name} data-id={item.id} />


Post a Comment for "Get Id Of Selected Item In Datalist"