Total Pageviews

Monday, 16 February 2015

Datepickers And Placeholders

Before discussing in depth about adding placeholder and date-picker together to a field lets just go through the code of adding a placeholder to any field, For Eg: password field

password1 = forms.CharField(label=_("Password"),
widget=forms.PasswordInput(attrs={'placeholder': 'Password'}))
This beautifully adds the placeholder called Password to the password textbox.

Now similarly if we do the same for Date Field we will get place holder for Date field too, but if we add the Jquery date picker Ui then only one of the class i.e either datepicker or placeholder gets focus and only datepicker calender appears and not the placeholder.

The above problem can be solved by exploring HTML5. We can use power of HTML5 to set the placeholder along with date picker. The beauty of this will be that placeholder will be displayed as watermark in the textbox. And this has nothing to do with jQuery UI Datepicker, its power of HTML5.

Follow the following steps:

Step 1: Make the below changes in forms.py

from functools import partial
DateInput = partial(forms.DateInput, {'class': 'datepicker'},)
dob = forms.DateField(label=_("dob"),
widget=DateInput())

Step 2: Make the below changes in Template having the Dob field. Add the above code within <head> </head> tags of the html file.

<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<script>
$(document).ready(function() {
    $('.datepicker').attr("placeholder", "Select a date").datepicker();

});
    </script> 


This should allow both placeholder and date picker to come simultaneously. The whole idea behind it is the placeholder is the hint for the textbox that can be obtained using power of HTML5

No comments:

Post a Comment