I want to create a function afficher() / print() that shows the name and email of the selected option
// ajouter() = add()
// supprimer() = delete()
// afficher() = print()
function ajouter() {
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 supprimer() {
let del = document.getElementById("list");
del.remove(del.selectedIndex);
}
// function afficher(){
// 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="ajouter()">Ajouter</button>
<button type="button" onclick="supprimer()">Supprimer</button>
<button type="button" onclick="afficher()">Afficher l'addresse</button>
<br><br>
<select name="names-list" id="list" size="5" style="width: 200px;">
</select>
</form>
You need to move myList = [] outside the functions
Here is a fully working version
Uncomment the parts with localStorage to save the list
const myListString = null// localStorage.getItem("list");
const myList = myListString ? JSON.parse(myListString) : [];
const list = document.getElementById("list");
function ajouter() {
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 supprimer() {
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 afficher() {
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="ajouter()">Ajouter</button>
<button type="button" onclick="supprimer()">Supprimer</button>
<button type="button" onclick="afficher()">Afficher l'addresse</button>
<br><br>
<select name="names-list" id="list" size="5" style="width: 200px;">
</select>
</form>