First, I did find a couple links that appeared to address this problem, but my understanding of javascript (and code in general) is pretty bad, and the solutions/explanations were difficult for me to generalize here. I know it has to do with a closure (which I vaguely understand).
Background: I created 10 checkboxes using a loop, each with 4 radio buttons that are supposed to appear when the checkbox is checked. I can accomplish the "appear/disappear" by creating 10+ functions one-by-one, but I would prefer to create my ten functions with a loop. The code below shows how each checkbox is calling a variable function on change (e.g., t0Disp()).
<?
for ($row = 0; $row <10; $row++)
{
$topic = $topic[$row];
?>
<input id="C<? echo $row ?>" type="checkbox" value="true" onchange="t<? echo $row ?>Disp()" /><? echo $topic ?>
<br />
<div id="<? echo $row ?>div" style="display: none">
<? for ($col = 0; $col < 4; $col++)
{
?>
<input type="radio" name="r<? echo $row ?>" value="<? echo $col ?>" onchange="disable<? echo $col ?>(); disable<? echo $row ?>();" />
<? echo $col+1; ?>
<?
}
?>
<br />
<br />
</div>
<?
}
?>
The code above works fine if I manually input my t0Disp() through t9Disp() functions. When I tried making a for-loop to create these functions (below), the function only works for t9Disp()
for (var i=0; i<10; i++) {
var idiv = i + "div";
var eldiv = document.getElementById(idiv);
var ci = "C" + i;
var elci = document.getElementById(ci);
window['t' + i + 'Disp'] = function() {
if(elci.checked == true) {
eldiv.style.display = "inherit";
}
else {
eldiv.style.display = "none";
}
}
}
I just need to understand why the javascript loop doesn't just spit out 10 distinct functions in the way that my php loop spits out 10 distinct checkboxes?
Thank you!