Tips for differentiating between elements with identical values in an HTML datalist using Angular

My boss is insisting that I use a datalist in our website interface to select an employee, even though there's no way to determine if the user typed in the name or picked from the list. The challenge is that the list must only display full names, but when the form is submitted, I need the employee ID, not just their name. Using the name to find the ID could cause issues if there are multiple employees with the same name. While it may be unlikely to happen, my boss wants me to address this issue. Unfortunately, I'm limited to using a datalist and cannot consider any other options. Here's the code:

<input list="empl-list" type="text">                                   
<datalist id="empl-list">
<option *ngFor="let empl of employees" value="{{empl.name + ' ' + empl.surname}}">
</datalist>

I thought about adding a function to the option click event in the datalist to retrieve the employee's ID, but it seems that datalists don't have a click event. One potential solution could be to append a counter to duplicate surnames (e.g., "Jim William", "Jim William 2"...), but I'm unsure if my boss would approve this approach. I'd prefer to explore alternative solutions if possible. Any suggestions?

Answer №1

It may seem a little strange, but you can utilize a variable and ngModel in this manner

  favoriteFlavor:any;
  iceCreamOptions=[
    {value:0,text:"Chocolate"},
    {value:1,text:"Coconut"},
    {value:2,text:"Mint"},
    {value:3,text:"Strawberry"},
    {value:4,text:"Vanilla"}
  ]
  getFlavorName(favoriteFlavor) {
    if (!favoriteFlavor) return '';
    const selectedOption = this.iceCreamOptions.find((x) => x.value == favoriteFlavor);
    return selectedOption ? selectedOption.text : favoriteFlavor;
  }



<label for="ice-cream-choice">Choose your favorite flavor:</label>
<input  [ngModel]="getFlavorName(favoriteFlavor)" (ngModelChange)="favoriteFlavor=$event"  list="ice-cream-flavors" id="ice-cream-choice" name="ice-cream-choice" />

<datalist id="ice-cream-flavors">
    <option *ngFor="let option of iceCreamOptions" [value]="option.value">
         {{option.text}}
    </option>
</datalist>
Your Favorite Flavor: {{favoriteFlavor}}

Observe how the variable "favoriteFlavor" receives the value of the selected option

View it in action on stackblitz

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ensure Safari sends the Origin header in jQuery GET requests

When I send a request from https://app.example.com, the following code is executed: $.get('https://api.example.com', { foo: 'bar' }) .success(getSuccess) .error(getError); This script runs smoothly on Chrome and Firefox, however, ...

Retrieving data and parameter data simultaneously from the ActivatedRoute

I am currently utilizing Angular and have a webpage where I need to send data to another page. Transmit an array of selected values Generate multiple records (associating with a model) this.activatedRoute.data.subscribe(({ model] }) => { setTim ...

React's .map is not compatible with arrays of objects

I want to retrieve all products from my API. Here is the code snippet for fetching products from the API. The following code snippet is functioning properly: const heh = () => { products.map((p) => console.log(p.id)) } The issue ari ...

Issue with Next.js: Callback function not being executed upon form submission

Within my Next.js module, I have a form that is coded in the following manner: <form onSubmit = {() => { async() => await requestCertificate(id) .then(async resp => await resp.json()) .then(data => console.log(data)) .catch(err => console ...

Refresh Chart Information using Ng2-Charts in Charts.js

Utilizing chart.js and ng2-charts, I am developing gauge charts for my platform to monitor the fluid levels inside a machine's tank. The values are retrieved from an external API, but I am encountering an issue where the charts are rendered before I ...

Access uninitialized properties in Typescript post-compilation

I am currently in the process of creating a wrapper for socket.io. Coming from a strong object-oriented background, I aim to incorporate the idea of Models into my framework/wrapper. For those familiar with socket.io, you may know that data associated wit ...

Can files in a directory be listed using JavaScript without the need for HTML tags?

Currently, I am exploring ways to automate an Angular application using Protractor. During this process, I encountered a situation where I needed to retrieve a list of all the files within a specific folder. In Java, I am aware that we can accomplish this ...

Is it possible that the passing of Form Serialize and list to the controller is not functioning properly?

i am struggling with the following code in my controller: public ActionResult SaveWorkOrder(DTO_WorkOrder objWork, List<DTO_PartsWO> listTry) { //something } here is my model : public class DTO_WorkOrder { public string Id { get; set; ...

I am unable to retrieve data using JavaScript

I am struggling to fetch data with JavaScript and display it in the console. Can anyone point out what I might be doing incorrectly? main.js // ADD TO CART $("#addToCartBtn").on('click',function(){ var _qty=$("#productQty") ...

Handling events with ReactJS can be made even more powerful by passing parameters to

Just dipping my toes into the world of ReactJs and I've put together a component to display a list of buses. My goal is to enable edit and delete functionality for each bus, but I'm struggling to pass the corresponding busId to my edit/delete met ...

Tips for passing input fields from a React Function component to a function

How can I retrieve the values from 4 input fields in my react functional component using a function called contactMeButtonPressed? The inputs include name, email, company name, and message when the contact me button is clicked. Do I need to implement stat ...

The integration of PHP code with an HTML form is causing issues

When I use the insert_teacher('bla bla','bla bla','dqsd') function in a PHP file, everything works fine. However, when I try to implement it with an HTML form, nothing is displayed and no data is inserted into my database. &l ...

Utilizing jQuery to Determine Character Count

I've tried everything on the site, but nothing seems to be working. I'm attempting to create a function that triggers when the character count in a div exceeds a certain number, but it's not functioning as expected. Any assistance would be g ...

Should the input field only contain spaces, a validation error will be triggered by the user

I am currently working on an Angular form implementation that allows users to enter their phone numbers. I have integrated a custom directive called appPhoneExtMask for formatting the phone numbers and have also implemented Angular form validation for both ...

Is there a way to prevent the conversion of .json/.webmanifest URLs into base64 strings?

I've been grappling with an issue for quite some time now. In my VSCode vite-react-typescript project, I have a link in the index.html file pointing to a webmanifest, which is essentially a json file with a different extension. After building my app, ...

"The custom input component still displays a required error message even after all fields have been filled

After implementing the ControlValueAccessor interface to create a custom input component and setting the required property to true for form validation, I am facing an issue where the input field still shows a "required" error even when it is filled. The mo ...

Script on the server side fails to execute following validation of form

Hey there, I'm struggling with my signup form. I want to submit the form using ajax after completing validation. I've used a jQuery plugin for validation, but whenever I click on any field, the ajax request is automatically sent to the server and ...

Optimizing normals for unindexed BufferGeometry in Three.js

Currently, I am attempting to refine the normals of a mesh starting from an non indexed BufferGeometry. A similar query has been addressed in the past, however, the Three.js API has undergone significant changes since then and I am unable to make it work o ...

Remove the ability to select from the dropped list item

Here is the HTML and Javascript code I used to enable drag and drop functionality for list items from one div to another: HTML: <div class="listArea"> <h4> Drag and Drop list in Green Area: </h4> <ul class="unstyle"> & ...

JavaScript loop used to create markers on Google Maps

I am currently in the process of developing a basic Google map which includes markers and involves looping through the data source for the markers. When I replace key.lng or key.lat with hardcoded values in the code below, everything functions correctly. ...