tags:

views:

72

answers:

2

Hello,

I wrote a datepicker in Javascript, but it is not working properly, as I lose the reference to the Calender object.

here is the example

http://asexpress.de/calender/

by clicking within the input field the calender will be displayed.

What should I do that the reference to the Calender object remains in contact.

A: 

From what I can tell so far of your script, the following code block:

Kalender.prototype.writeMonth = function() {
  var that = this;

contains some code further down:

  else if ( this.isToday(displayNum, length) && this.isLink(displayNum, length) )  
    {
      sbuffer.push('<td class="date" onClick="that.changeDate(this,\''
                      + this.id + '\'); that.returnDate('+ this.month +','+ this.year+')">' + displayNum + '</td>');
    } 

This would cause a problem, since the that variable is declared within the scope of this function and the onclick event will fire outside of the scope. IMO, building the HTML isn't the best method here. It would be best to build the table cells using the DOM and add event handlers that are inside the scope of the function. This happens a few times.

FYI, you're using eval() rather unnecessarily in your code:

this.months = eval("config.language."+ this.options['language'] +".months");

// Can also be written as:
this.months = config.language[this.options['language']].months;

See Eval is Evil for more information.

Further Reading

MSDN - Building Tables Dynamically
MDC - Traversing an HTML table with JavaScript and DOM Interfaces
MDC - Working with Closures

Andy E
Thanks for the help. Can you please have a look at the code and further advice me?
A: 

You should declare the variable which holds datepicker object globally.

var kalender;
var kalender2;

function reisedate(d) {
    document.getElementById("abc").value = d.getDate() + "/" + parseInt(d.getMonth()+1) + "/" + d.getFullYear();
}

// rest of the code

Take a look at first two lines.

Balon
You would have to do this for each instance of a datepicker object, though. I would recommend correctly using closures to achieve full code portability.
Andy E
I fully agree with you :)
Balon