Hi, I have come with a solution but the condition “else” does not work, although I have no idea why. Can you help please?
Task:
40. Simple phone book.
In this assignment, we will create a simple telephone directory, where the user can search by name to retrieve the telephone number.
- Create an object.
- Fill the object with the following relations. The name should be key and the phone number should be the value:
- Have the user enter a name, then print the phone number that belongs to that name. If the user enters a name that does not exist in the object, give an error message stating that we have not saved this number.
My solution:
<input type="text" id="name" placeholder="Enter name">
<button type="button" id="button">Find number</button>
<p id="phone"></p>
<script>
var phonebook = {Carlos:22334455,
Gabba:95959595,
Ivo:97959795,
Fabrice:12345678};
$("#button").click(function(){
var enteredName = $("#name").val();
$.each(phonebook, function(index, value){
if(index == enteredName) {
var phoneNumber = value;
$("#phone").text("Phone number is: "+phoneNumber);
}
else {
$("#phone").text("Sorry, name was not found in database.");
}
});
});
</script>
It’s really tricky. Because if I delete the line with condition “else”:
else {
$("#phone").text("Sorry, name was not found in database.");
}
then it works normally, like this: I enter a name from the phonebook (for example “Carlos”) and it gives me “Phone number is: 22334455”. Which is correct.
However if name was not found in object then I need to write “Sorry, name was not found in database.”. So I added simple “else” condition described above. But it gives me “Sorry, name was not found in database.” in all situation no matter the name entered, even though the name is in the object.
I can’t understand that. Can you help me please? I have also other working solution, but I need to figure out this one. Thanks!