views:

28

answers:

1

Hi.

I have several textboxes, 6 to be precise. What I want is that whenever I click one of them, the current date appears on the box I just clicked.

I have this so far:

function dat() {
        var year=document.frm._data1
        var currentTime = new Date()
        var month = currentTime.getMonth() + 1
        var day = currentTime.getDate()
        if (day <10) {
            day = "0" + day
        }
        var year = currentTime.getFullYear()
        theDate.value = year + "-" + month + "-" + day
        }

_data1 refers to the one of the textboxes. How can It works, but for just that box. How can I do this, using "this", besides having to write a function for every single textbox.

+2  A: 

You can write the function once, and apply it to each checkbox:

function dat() {
    // Calculate current date into year, month and day variables
    this.value = year + '-' + month + '-' + day ;
}
document.getElementById('textbox1').onclick = dat ;
document.getElementById('textbox2').onclick = dat ;
Gus
can't get it work like that.
elvispt
I have put my code at http://www.jsfiddle.net/ssbCr/
Gus
Put all your initialization (...onclick = dat;) in a function that you assign to window.onload.
Edgar Bonet
OK got it to work. Thank you Edgar and Gus. oh and thank for letting me know about http://www.jsfiddle.net/. Great place. :)
elvispt