I aim to design a feature that will display both the full name and email address of the chosen selection

I need to develop a function display() / print() that will display the name and email of the selected option

// add() = ajouter()
// delete() = supprimer()
// display() = afficher()

function add() {

  let fullName = document.getElementById("name").value;
  let mail = document.getElementById("email").value;

  myList = [];
  myList.push({
    name: fullName,
    email: mail
  })

  document.getElementById("list").innerHTML += '<option>' + fullName + '</option>' + '<br>';
}

function delete() {
  let del = document.getElementById("list");
  del.remove(del.selectedIndex);
}


//     function display(){

//     let show = document.getElementById("list")
//     let showName = myList[show.selectedIndex].name,
//         showEmail = myList[show.selectedIndex].email;

//     alert("Hello " + showName + " Your email is : " + showEmail);

// }
<form action="">
  <br><br>
  <label for="name">Full name : <input id="name" type="text"></label><br><br>
  <label for="email">Email : <input id="email" type="email"></label><br><br><br>

  <button type="button" onclick="add()">Add</button>
  <button type="button" onclick="delete()">Delete</button>
  <button type="button" onclick="display()">Display Address</button>
  <br><br>
  <select name="names-list" id="list" size="5" style="width: 200px;">

  </select>
</form>

Answer №1

To optimize your code, remember to declare myList = [] outside of the functions

Check out this updated version for a fully functional solution

Don't forget to uncomment the sections related to localStorage for saving the list

const myListString = null// localStorage.getItem("list");
const myList = myListString ? JSON.parse(myListString) : [];
const list = document.getElementById("list");

function addEntry() {

  let fullName = document.getElementById("name").value;
  let mail = document.getElementById("email").value;

  myList.push({
    name: fullName,
    email: mail
  })
  list.add(new Option(fullName));
  // localStorage.setItem("list", JSON.stringify(myList))
}

function removeEntry() {
  const fullName =  document.getElementById("name").value;
  const idx = myList.findIndex(item => item.name === fullName)
  if (idx != -1) {
    myList.splice(idx,1)
    list.options[idx].remove()
  }
}

function displayEntry() { 
  const idx = list.selectedIndex;
  const person = myList[idx]
  alert("Hello " + person.name + " Your email is : " + person.email);
}
<form action="">
  <br><br>
  <label for="name">Full name : <input id="name" type="text"></label><br><br>
  <label for="email">Email : <input id="email" type="email"></label><br><br><br>

  <button type="button" onclick="addEntry()">Add</button>
  <button type="button" onclick="removeEntry()">Remove</button>
  <button type="button" onclick="displayEntry()">Display Address</button>
  <br><br>
  <select name="names-list" id="list" size="5" style="width: 200px;">
  </select>
</form>

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

Issue with Angular 2 NgFor Pattern Error Message Display Absence

I am attempting to incorporate inputs with a regex requirement within an ngFor loop, but I am not receiving the expected error message when entering something that does not match the required pattern. Even when I input an incorrect pattern, "Test" remains ...

Learn how to transfer information via WebSocket when the connection closes in a React/NextJS application during a page reload or tab

In the development of my web application, I am implementing a feature to display the online/offline status of users. In order to achieve this functionality, I have to listen for both close and open events of the websocket. const ws = new WebSocket('ws ...

The script is not functioning properly due to an error stating "(Uncaught ReferenceError: $ajaxUtils is not defined)"

I'm having trouble figuring out what the issue is (Uncaught ReferenceError: $ajaxUtils is not defined) document.addEventListener("DOMContentLoaded", function (event) { showLoading("#main-content"); $ajaxUtils.sendGetReque ...

The ngModel directive seems to be failing to bind the select element in Angular 4

One of the challenges I am facing in my application involves a form that includes various data fields such as title, price, category (select), and imageUrl. I have successfully implemented ngModel for all fields except the select element. Strangely, when I ...

Exploring the attributes of optional features

Dealing with optional properties can be quite tedious. Consider the object test1 in TypeScript: interface Test { a?: { b?: { c?: { d?: string } } }; } const test1: Test = { a: { b: { c: { d: 'e' } } } }; Handling the absence of each proper ...

Utilizing the sAjaxSource property in Datatables to fetch data through Ajax from multiple tables while dynamically passing arguments

I am facing an issue with populating two datatables using data retrieved from a flask API through a GET request. My data source URL is localhost:5000/data, but for some reason, I am unable to display the data in the datatables. Interestingly, when I use a ...

What may be causing a configuration problem with the USB binding in Electron?

I am encountering difficulties with installing USB modules in my electron app. Every time I attempt to install electron and its dependencies, I encounter the issues outlined below. Can someone please assist me in resolving this? If anyone has faced a simi ...

The 'admin' attribute is not found in the 'Object' data type

I have been facing this issue for quite some time now. The backend API response is indicating that a certain property does not exist, even though it clearly does. My Angular application suddenly started showing 18 errors today, and I am at a loss on how ...

How about checking the memory usage in Javascript?

Similar Question: Looking for a Javascript memory profiler I am curious about determining the memory consumption of variables in JavaScript. Could it be done at all? ...

Acquire Content using jQuery and Navigate page horizontally

I am trying to achieve a unique effect by capturing content x and horizontally scrolling the page while the mouse is in motion, similar to swiping on a tablet. It seems simple enough.. Capture clientX on mousedown, ScrollLeft by ClientX while moving, Di ...

Tips for retaining the original size of an image in HTML5 canvas drawImage

function getBase64ImageData(_id) { var canv = document.createElement('CANVAS'); var context = canv.getContext("2d"); var imageElem = document.getElementById(_id); context.drawImage(imageElem, 0, 0); var dataURL = canv.toDat ...

Firefox browser does not display flashing titles for tabs

Every second, I want to display "New message..." in the title when the browser tab is inactive or the user is in another tab. Here's the code I used: <script> var mytimer; function log() { document.title = document.title == "" ...

What is the best way to use element.appendChild to generate a link?

I am currently utilizing the following snippet of Javascript to extract information from the current webpage using a browser extension. I have only included a portion of the code that is relevant, as the full script is quite lengthy. The code works perfect ...

Encountering a npm error E404 when trying to install unicons package for React development

I recently started working on a weather app project using create-react-app and encountered an issue while trying to install unicons for the project. Despite attempting a few solutions, I was unable to resolve the problem. Here is the command I used for th ...

The dynamic alteration of BackgroundImage does not appear to be functioning correctly with tailwind and nextjs

Introduction While working on my weather application using nextJS and TailwindCSS, I encountered a UI issue towards the end of development. Unfortunately, I couldn't resolve this problem alone. My main concern is changing the background image dynami ...

Tips for concealing the values within a selected dropdown list using jQuery

Hello, I'm currently working on a jQuery application that involves a dropdown list box and a gridview. The first column of the gridview has checkboxes with a check all button at the top. My goal is to disable corresponding values in the dropdown list ...

Transforming a text file into an array using fs in Node.js

My text file contains the following: {"date":"2013/06/26","statement":"insert","nombre":1} {"date":"2013/06/26","statement":"insert","nombre":1} {"date":"2013/06/26","statement":"select","nombre":4} Is there a way to convert the text file contents ...

What are the steps to run and test the renovate bot on your local machine

Before setting up renovate to work with my Azure pipeline, I wanted to test it locally using npx renovate to ensure everything is working as expected and that my config file is properly configured. I ran npx renovate --platform local command. My project i ...

Updating the user interface in react-apollo following a delete mutation

After successfully executing a delete mutation in my React Apollo component, the UI of my app did not update as expected. Here is the code snippet for reference: const deleteRoom = async (roomId, client = apolloClient) => { const user = await getUser ...

Conceal a div and label after a delay of 5 seconds with a JavaScript/jQuery function in C#

Here is a sample div: <div class="alert alert-success alert-dismissable" runat="server" visible="false" id="lblmsgid"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> ...