Greg Smith

Web Developer

loading

Automatically add a jQuery date picker to an input box with a specific class

No comments

The jQuery UI project comes packed with a nice little datepicker which you can add to a textbox field.

datepicker

Once you’ve included the jQuery and jQuery UI JavaScript files on your Web site, you need to add in some JavaScript to add the datepicker to a particular form element:

1
2
3
$(function() {
    $( "#datepicker" ).datepicker();
});
$(function() {
	$( "#datepicker" ).datepicker();
});

If you plan to have multiple datepicker fields across your site, here’s a little snippet which you can use instead of the above code that will automatically add a datepicker to any textbox with the class “date”:

1
2
3
4
5
$(document).ready(function() {
    $('.date').each(function() {
        $(this).datepicker({ dateFormat: 'yy-mm-dd' });
    });
});
$(document).ready(function() {
	$('.date').each(function() {
		$(this).datepicker({ dateFormat: 'yy-mm-dd' });
	});
});

Just add this code to your site footer, or into some globally-included JavaScript file, and then create your form element:

1
<input type="text" name="date" class="date" />
<input type="text" name="date" class="date" />

Create as many of these as you like; they’ll all be automatically converted into datepickers. Easy!

Post a Comment

Your email is never shared. Required fields are marked *

*
*