I'm trying to disable a few textboxes in a table using JavaScript.
My JavaScript
var table = {
disableTextbox: function() {
var rows = document.querySelectorAll('table tr');
rows.forEach(function(row, index) {
if (index === 1 || index === 7) {
return;
}
var variable1 = row.cells[3];
var variable2 = variable1.querySelector('input[type="text"]');
if (variable2) {
var variable3 = document.getElementsByTagName('td');
variable3.disabled = true;
}
});
}
};
table.disableTextbox();
<tr>
<td>Employee Name:</td>
<td>Schedule Time:</td>
<td>Tasks Done:</td>
<td><input type="text" name="yesOrNo" /></td>
</tr>
My HTML for one of the rows of the table. I didn't want to include all 10 lines because that's just a lot to put here and everything is the same except for text with the tags (for example, people's names that I didn't want to include on here)
All suggestions are appreciated! Thanks!
There's a couple of issues in your code.
Firstly
getElementsByTagName()returns a NodeList, not a single element. Therefore you would need to loop through the list and set every Element within it todisabled, not the NodeList itself.Secondly a
tdhas nodisabledproperty. That only applies to theinput, so you're targetting the wrong element.That being said, your code is a lot more complex than it needs to be. You can simplify it using
querySelectorAll()and a combination of:not()and:nth-child()to leave the second and eighth rows enabled: