Search code examples
javascriptformscountdown

use one countdown script for multiple countdowns


I want to use a countdown script like this

     var montharray=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")

function countdown(yr,m,d,idCountdown){
    var theyear=yr;
    var themonth=m;
    var theday=d;
    var today=new Date();
    var todayy=today.getYear();
    if (todayy < 1000)
        todayy+=1900
    var todaym=today.getMonth();
    var todayd=today.getDate();
    var todayh=today.getHours();
    var todaymin=today.getMinutes();
    var todaysec=today.getSeconds();
    var todaystring=montharray[todaym]+" "+todayd+", "+todayy+" "+todayh+":"+todaymin+":"+todaysec;
    var futurestring=montharray[m-1]+" "+d+", "+yr;
    var dd=Date.parse(futurestring)-Date.parse(todaystring);
    var dday=Math.floor(dd/(60*60*1000*24)*1);
    var dhour=Math.floor((dd%(60*60*1000*24))/(60*60*1000)*1);
    var dmin=Math.floor(((dd%(60*60*1000*24))%(60*60*1000))/(60*1000)*1);
    var dsec=Math.floor((((dd%(60*60*1000*24))%(60*60*1000))%(60*1000))/1000*1);
    var dag = "dagen";

    if(dday==0&&dhour==0&&dmin==0&&dsec==1){
        document.getElementById(idCountdown).value=current;
        return;
    }
    else if(dday<=1) {
        dag = 'dag';
    }
    document.getElementById(idCountdown).value=dday+ ' ' + dag + ' ' +dhour+" uur "+dmin+" min "+dsec+" sec";
    setTimeout(function(){countdown(theyear,themonth,theday,idCountdown);}, 1000);
}

in my html page i will have a textfield like this

 <input name="aktie1" type="text" class="countdownTekst" size="27" readonly="readonly">
 <input name="aktie2" type="text" class="countdownTekst" size="27" readonly="readonly">

Then i use this to use the function

countdown(2012,7,30, 'aktie1')

The last one is the ID for the textfield. But when i do it like this i will get an error

 document.forms.count.idCountdown.value is undefined

How do i get the id for that textfield in that function?


Solution

  • You need to access the input like this: document.forms.count[idCountdown].value

    EDIT: This fiddle is working http://jsfiddle.net/Fy2FM/4/ . The bigger problem is that you are not declaring the variables with var yourvar, and this makes the variables to be part of the global object. Because of this, you were always seeing the same in both countdowns, because in fact you were accessing the same variables.