-1

I try to have a Date Mask as MM/DD/YYYY appear as soon as user click on a textbox using only JavaScript or Typescript with using jQuery or any template. I have this JavaScript code:

function DateFormat() {
var date = this.value;
if (date.match(/^\d{4}$/) !== null) {
    this.value = date + '-';
} else if (date.match(/^\d{4}\-\d{2}$/) !== null) {
    this.value = date + '-';
}
 }
<input type="text" onclick="DateFormat();">

but I am getting this error:

Cannot read property 'match' of undefined

I would like to mask appeard like --/--/--when I click on the text box.

nakisa
  • 89
  • 1
  • 2
  • 6

1 Answers1

1

The problem is that "this" isn't set to the input in the function, so this.value doesn't refer to anything. Try the following:

function DateFormat(input) {
    var date = input.value;
    if (date.match(/^\d{4}$/) !== null) {
        input.value = date + '-';
    } else if (date.match(/^\d{4}\-\d{2}$/) !== null) {
        input.value = date + '-';
    }
 }
<input type="text" onclick="DateFormat(this);">
AmericanUmlaut
  • 2,817
  • 2
  • 17
  • 27