If you’ve ever tried to put a placeholder attribute on a date input like so :
<input type="text" name="myDateField" placeholder="Enter the date here" />
You know it doesn’t work.
Instead what you end up with is the field being pre-populated with “dd/MM/yyyy” which is incredibly annoying! But there is actually a way to get the placeholder working by instead making the input function as a textbox until clicked, and then quickly swapping it to act like a date input.
First we need to change out input to be of type “text” like so :
<input type="text" name="myDateField" placeholder="Enter the date here" />
We are now going to create a new directive. In my case I named it DynamicDateInputDirective. The contents of which is :
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: 'input[dynamic-date-input]'
})
export class DynamicDateInputDirective {
private element : ElementRef;
constructor(element : ElementRef) {
this.element = element;
}
@HostListener('focus')
handleFocus()
{
this.element.nativeElement.type = 'date';
}
@HostListener('blur')
handleBlur()
{
if(this.element.nativeElement.value == "")
{
this.element.nativeElement.type = 'text';
}
}
}
What does this do?
- We use the HostListener to bind to the focus event, on focus, we ensure that the field is of type “date”.
- We then use the HostListener to bind to the blur event (So focus is moving away from the field). We check to see if the field is empty, if it is, return it to the “text” type. What this means is if someone clicks into the field but doesn’t enter anything and moves away, we keep our placeholder.
You can then add the directive to your text input :
<input type="text" name="myDateField" dynamic-date-input placeholder="Enter the date here" />
Not using Angular? The paradigm is the same if you are using React, jQuery or even Vanilla JS. On focus you need to change your text type to date, and then on blur you need to do the reverse (Remembering to only do it if the value is empty).
💬 Leave a comment