0

I'm making a calendar script and it works ok with the Opera browser, but not with firefox. The trouble happens in the day selection. This particular snippet illustrates the problem. In this case, dayofweek[] contains 31 DIV tags each containing its own number that people can click on.

<script type="text/javascript">
var maxdays=31;
for (var n=1;n<=maxdays;n++){
dayofweek[n].onclick="selectday("+n+")";
}

function selectday(day){alert(day+" is selected");}
</script>

This script works (in opera) by printing a message that the correct number is selected. In Firefox, the onclick event never is executed even tho I made clicks..

The other method I tried is this:

<script type="text/javascript">
var maxdays=31;
for (var n=1;n<=maxdays;n++){
dayofweek[n].onclick=function(){selectday(n);}
}

function selectday(day){alert(day+" is selected");}
</script>

This time, both firefox and opera respond, but the problem is that "31 is selected" appears no matter which number I select.

Does anyone know what I can do to make all javascript enabled internet browsers cooperate with my code?

1 Answers1

0

Javascript is not block scoped. Try this:

<script type="text/javascript">
var maxdays=31;
for (var n=1;n<=maxdays;n++){
    dayofweek[n].onclick=selectdaywrapper(n);
}

function selectdaywrapper(day) {
    function selectday(){
        alert(day+" is selected");
    }
    return selectday;
}
</script>

The issue you are running into has to do with scoping and how variables are bound in js. The functions you are creating in the loops are binding to the loop variable, but are not evaluated till after the loop finishes, so all the onclick events are executing with the final value of n

Drew Faubion
  • 441
  • 3
  • 12
  • I wouldn't have thought of a function in a function but that idea does work. What I don't get tho is how day manages to retain its value at the alert function when it looks like nothing is passed into selectday –  Sep 03 '14 at 04:47
  • It's actually one of the most common mistakes made by beginning javascript developers (hence, minitech has marked your question as duplicate). The trick is to understand scoping and closures in javascript. Here is an article which contains an explanation of the issue http://robertnyman.com/2008/10/09/explaining-javascript-scope-and-closures/#highlighter_546762 There was a great google tech talk about it, but I can no longer find it. – Drew Faubion Sep 03 '14 at 20:17