I want the nearest input field to be disabled when I click on a checkbox. Because I dont want repetitive code for each id like:
document.getElementById('checkBox').onchange = function() {
document.getElementById('textBox').disabled = !this.checked;
};
I decided to use class and a function. But right now nothing is happening and there are also no errors.
This is my code:
<form action="" method="get">
<input type="checkbox" class="checkBox" name="player1" value="check" checked> <input type="text" class="textBox" name="player1Name" value="Player1"><br /><br />
<input type="checkbox" class="checkBox" name="player2" value="check" checked> <input type="text" class="textBox" name="player2Name" value="Player2"><br><br />
<input type="checkbox" class="checkBox" name="player3" value="check"> <input type="text" class="textBox" name="player3Name" value="Player3" disabled><br /><br />
<input type="checkbox" class="checkBox" name="player4" value="check"> <input type="text" class="textBox" name="player4name" value="Player4" disabled><br /><br />
<input type="submit" value="Play game!">
</form>
<script>
function getClosest(el, tag) {
// this is necessary since nodeName is always in upper case
tag = tag.toUpperCase();
do {
if (el.nodeName === tag) {
// tag name is found! let's return it. :)
return el;
}
} while (el = el.parentNode);
// not found :(
return null;
}
document.getElementsByClassName('checkBox').onchange = function() {
var closestInput = getClosest(this, input);
closestInput.disabled = !this.checked;
};
</script>
JSFiddle: https://jsfiddle.net/8an1h0ys/