nemo_87 nemo_87 - 3 months ago 7
HTML Question

innerHTML always returns 'undefine' in javaScript

I have one table in HTML and what I am trying to do is to find second column inside of it and get it's values into a string array.

Later I want to do simple if check and see if the value I have entered in one text box already exists in that array. But I keep getting 'undefine' both when I try to get .innerHTML for text box or .innerHTML for array element. I have tried with .value and .innerText as well, but I was getting same result.

I only can use plain javaScript, so no jQuery or other libraries. What I am missing here?

Here is my HTML for table:

<table id="results" width="360" border="1">
<thead>
<tr>
<th scope="col" width="120">Date Created</th>
<th scope="col" width="120">Name</th>
<th scope="col" width="120">Tests</th>
</tr>
</thead>
<tbody>
<tr/>
<td>07/08/2015</td>
<td>Test Name</td>
<td>Raven</td>
</tr>
<tr/>
<td>01/08/2017</td>
<td>Test Name 2</td>
<td>PCT</td>
</tr>
</tbody>
</table>


This is HTML for text box:

<form name="formTestInfo" method="post">
Name:<br>
<input type="text" id="tbName" name="tbName">
<p id="nameVal"></p>
</form>


And this is my script code:

var secondCell = document.querySelectorAll('td:nth-child(2)');
var cellValues = [];
secondCell.forEach(function(singleCell) {
cellValues.push(singleCell.innerText);
});

for(var i=0; i < cellValues.length ; i++)
{
if(document.getElementById("nameVal").innerHTML == cellValues[i].innerHTML)
{
var nameVal = "Name already exists in table!";
validation = false;
}
}


I never get inside if because values are never find, but array is filled in with correct values. Somebody sees what is wrong here?

Answer

try this :

var secondCell = document.querySelectorAll('td:nth-child(2)');
var cellValues = [];
secondCell.forEach(function(singleCell) {
cellValues.push(singleCell.innerText);
});

for(var i=0; i < cellValues.length ; i++)
{
    if(document.getElementById("tbName").value == cellValues[i])
    {
      var nameVal = "Name already exists in table!";
      validation = false;
    }
}