Im quite new to coding, but Ive finished lots on freecodecamp and made som simple guess games I learned on mozilla.developer. Im using visualStudioCode and practicing. Problem: I want to write a first name in the input="text" field, submit it, then the paragraph-tag should log the last name of the entered first name. Ive made two objects as users in my webpage. Ive goten far enough to make the console log the name in the parameter, but.. As I see it, the function findPerson(name) parameter must be engaged by the inputField. How do I do this? Here is my code.
<html>
<div class="form">
<label for="inputField"> Enter a users first name, and see their last name. </label>
<input type="text" class="inputField" id="inputField" placeholder="Enter search here">
<input type="submit" class="submitBtn" id="submitBtn" value="Search">
</div>
<p class="searchResult">Last name will be shown here.</p>
</html>
<script>
const people = [
{
firstName: "Arnold",
lastName: "Schwarzenegger",
hobbies: ["Get pumped", "be awesome"],
},
{
firstName: "Clint",
lastName: "Eastwood",
hobbies: ["Make movies", "not being Arnold"],
},
];
const btn = document.querySelector(".submitBtn");
const inputF = document.querySelector(".inputField");
const para = document.querySelector(".searchResult");
function findPerson(name) {
let word = String(inputF.value);
word = name;
for(var i = 0; i < people.length; i++) {
if(people[i].firstName == name) {
para.textContent = people[i].lastName;
return people[i].lastName;
}
else {
para.textContent = "Not found";
}
}
};
btn.addEventListener("click", findPerson);
</script>
What you are doing is your findPerson function takes name as in argument.
function findPerson(name)
However, that name argument is not the value of the textbox..
Then in the next line you DO get the value of the textbox and you call it 'word'
let word = String(inputF.value);
But then in next line you overwrite that word variable again with the name variable.
word = name;
Then you check the firstname of all peoples with the name variable, but as said above, this isnt the value of the textfield.
So, do not take an argument for the function. And make name the value of the textbox by doing:
function findPerson() {
let name = String(inputF.value);
....
}
And then it will work.