What I want to do: The function I want to do is compare and insert data into the input field, it should run through the firstName column in the table and compare with the firstName field in the array , if any of those is the same then it should print the value to the input field.
Problem: I have no idea how to check every row in the firstName column in the table and compare it to the firstName value in the array.
const student= ["Janet", "Weaver","Adam"];
let text = "";
student.forEach(myFunction);
student.forEach(element => console.log(element));
function myFunction(item) {
text += item + "<br>";
}
//Check the firstName column in table
//if(td = student.firstName){
//document.getElementById("janet").innerHTML = student.firstName;
//}
<!DOCTYPE html>
<html>
<style>
table,
th,
td {
border: 1px solid black;
}
</style>
<body>
<h2>User table</h2>
<table style="width:100%">
<tr>
<th>First name</th>
<th>Age</th>
<th>Caption</th>
</tr>
<tr>
<td>Janet</td>
<td>16</td>
<td><input type="text" id="janet" placeholder="Name"></input>*here should appear the name of Janet*
</td>
<tr>
<td>John</td>
<td>19</td>
<td><input type="text" placeholder="Name"></input>
</td>
</tr>
</table>
</body>
</html>
You should probably run throught your table rows, then compare the first column value with your Array
EDIT :
document.getElementsByTagName('tr') returns an HTMLCollection that needs to be converted to an Array to allow you to use forEach
Array.from(document.getElementsByTagName('tr')).forEach(function(row) {
let firstTD = row.getElementsByTagName('td').item(0);
if (firstTD === null) { return; }
let firstname = firstTD.innerHTML;
// does the array contain firstname?
if (student.indexOf(firstname)>=0) {
let input_col = row.getElementsByTagName('td').item(2);
let input = input_col.getElementsByTagName('input').item(0);
input.value = firstname;
}
});
Note that it would probably be easier to use IDs or classes instead of counting the tags with getElementsByTagName...