Reputation: 427
I've tried using the debugger but still don't understand why this function keeps printing out the first object in the array no matter what I enter.
What I want to do is to iterate through each array element and if the input from the text box is equal to one of the name properties, then print the information for that name.
I thought a simple for loop that checks if the input in the text box equals any of the name properties then console.log that array element would work.
HTML:
<script type = "text/javascript" src="js/ObjectTest.js"></script>
<input type = "text" name = "name" id = "name"> </input>
<button type = "submit" id = "submit" onclick = "findStudent()">Find Student </button>
Javascript:
var registeredStudents = [
{name: "Matthew", GPA: 5.0, Faculty: "Science", Major: "Cognitive Systems"},
{name: "Rohit", GPA: 5.0, Faculty: "Science", Major: "Micro-Biology"},
{name: "Marcel", GPA: 5.0, Faculty: "Engineering", Major: "Undeclared"},
{name: "Louis", GPA: 5.0, Faculty: "Engineering", Major: "Mechanical Engineering"},
{name: "Rob", GPA: 5.0, Faculty: "Engineering", Major: "Mechanical Engineering"}
];
function findStudent(){
var submit = document.getElementById('name');
for (var i = 0; i < registeredStudents.length; i++){
if (submit.value = registeredStudents[i].name){
console.log(registeredStudents[i]);
break;
} else if (submit.value != registeredStudents[i]){
console.log("Not a registered student");
}
}
}
Upvotes: 1
Views: 24
Reputation: 68393
You if condition is wrong, there should be ==
not =
function findStudent(){ var submit = document.getElementById('name'); for (var i = 0; i < registeredStudents.length; i++){ if (submit.value == registeredStudents[i].name){ console.log(registeredStudents[i]); break; } else if (submit.value != registeredStudents[i]){ console.log("Not a registered student"); } } }
Upvotes: 1