Reputation: 35
I am learning javascript and I am trying to make a table which will give us the result.
function showResult() {
var viewResult = document.getElementById('demo');
var inputOne = document.getElementById("studentName").value;
var inputTwo = document.getElementById("studentsubj").value;
var stuName = studentName.indexOf(inputOne);
var subName = subjectName.indexOf(inputTwo);
var result = markes[stuName][subName];
viewResult.innerHTML = "This is the marks of " + inputOne + " " + inputTwo + " " + result + " %";
}
In Console when I click the input button with blank input field I am getting an error in javascript
This is the error:
"demo.js:408 Uncaught TypeError: Cannot read property '-1' of undefined"
What's wrong with my code.
Upvotes: 3
Views: 151
Reputation: 2288
You should check if the student and subject are exists.
var studentName = ["Bruce", "Clark", "Barry", "Diana", "Victor", "Billy"];
var subjectName = ["English", "Math", "History", "Geography", "Physics", "Biology"];
var markes = [
[99, 98, 97, 98, 99, 90],
[98, 90, 96, 99, 98, 95],
[95, 98, 94, 90, 97, 91],
[99, 97, 94, 90, 96, 92],
[69, 89, 79, 59, 65, 90],
[50, 90, 91, 66, 70, 80]
];
function showResult() {
var inputOne = document.getElementById("studentName").value;
var inputTwo = document.getElementById("studentsubj").value;
var stuName = studentName.indexOf(inputOne);
var subName = subjectName.indexOf(inputTwo);
if (stuName < 0) {
alert("Student not found");
return;
}
if (subName < 0) {
alert("Subject not found");
return;
}
var result = markes[stuName][subName];
alert(result);
document.querySelector('input').value = "";
}
<table border="1" width="auto">
<tr>
<td>Name</td>
<td>English</td>
<td>Math</td>
<td>History</td>
<td>Geography</td>
<td>Physics</td>
<td>Biology</td>
</tr>
<tr>
<td>Bruce</td>
<td>99%</td>
<td>98%</td>
<td>97%</td>
<td>98%</td>
<td>99%</td>
<td>90%</td>
</tr>
<tr>
<td>Clark</td>
<td>98%</td>
<td>90%</td>
<td>96%</td>
<td>99%</td>
<td>98%</td>
<td>95%</td>
</tr>
<tr>
<td>Barry</td>
<td>95%</td>
<td>98%</td>
<td>94%</td>
<td>90%</td>
<td>97%</td>
<td>91%</td>
</tr>
<tr>
<td>Diana</td>
<td>99%</td>
<td>97%</td>
<td>94%</td>
<td>90%</td>
<td>96%</td>
<td>92%</td>
</tr>
<tr>
<td>Victor</td>
<td>69%</td>
<td>89%</td>
<td>79%</td>
<td>59%</td>
<td>65%</td>
<td>90%</td>
</tr>
<tr>
<td>Billy</td>
<td>50%</td>
<td>90%</td>
<td>91%</td>
<td>66%</td>
<td>70%</td>
<td>80%</td>
</tr>
</table>
<br>
<br>
<form>
<input type="text" id="studentName">
<input type="text" id="studentsubj">
<input type="button" name="submit" value="submit" onclick="showResult()" />
</form>
<p id=demo></p>
The same code HERE, Update for your link
Upvotes: 1
Reputation: 504
If the input field is blank var stuName = studentName.indexOf(inputOne);
and var subName = subjectName.indexOf(inputTwo);
will return -1. so var result = markes[stuName][subName];
will be var result = markes[-1][-1];
This is the reason of console error.
Upvotes: 0