Sunday, 4 October 2015

JQuery DatePicker: How do I add a watermark?

A watermark is always a great way to provider a meaningful hint to a user. Using the JQuery DatePicker control, I wanted to tell the user the expected format of the date.

 I added a new class called 'watermarkrequired' to the required html elements to help me identify them.

I looked at several option:
1. Using the blur and focus events.

$('.watermarkrequired').blur(function () {
if ($(this).val().length == 0)
   $(this).val(watermark).addClass('watermark');
}).focus(function () {
if ($(this).val() == watermark)
    $(this).val('').removeClass('watermark');
}).val(watermark).addClass('watermark');

2. Using the 'AppendText' option of the DatePicker

$( ".watermarkrequired" ).datepicker( "option", "appendText", "(yyyy-mm-dd)" );

Finally, I settled on the placeholder attribute

$( ".watermarkrequired" ).attr("placeholder", "dd/mm/yyyy");

No comments:

Post a Comment