Set default input values on jquery ui daterange picker inputs to be specific dates
I'm using jquery ui daterange datepicker http://jqueryui.com/demos/datepicker/#date-range my code is below it's pretty much the default initialization. I would like my "to" input field value to be todays date,and the "from" input field value to be 30 days prior. I haven't found anyway to set these input values dynamically, any help's appreciated
Thanks
<div id="date-wrapper">
<script>
$(function() {
var dates = $( "#from, #to" ).datepicker({
defaultDate: "+1w",
dateFormat: "M d, yy",
changeMonth: true,
numberOfMonths: 1,
onSelect: function( selectedDate ) {
var option = this.id == "from" ? "minDate" : "maxDate",
instance = $( this ).data( "datepicker" ),
date = $.datepicker.parseDate(
instance.settings.dateFormat ||
$.datepicker._defaults.dateFormat,
selectedDate, instance.settings );
dates.not( this ).datepicker( "option", option, date );
}
});
});
</script>
<label for="from"></label>
<input type="text" id="from" name="from"/><span style="font-weight:bold;font-size:15px;">-</span>
<label for="to"></label>
<input type=开发者_StackOverflow"text" id="to" name="to"/>
</div>
</div>
You'll need to initiate the two fields separately. You could save the settings to an object for reuse though.
The JavaScript would look something like:
var settings = {
dateFormat: "M d, yy",
changeMonth: true,
numberOfMonths: 1,
onSelect: function(selectedDate) {
var option = this.id == "from" ? "minDate" : "maxDate",
instance = $(this).data("datepicker"),
date = $.datepicker.parseDate(
instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
$("#from, #to").not(this).datepicker("option", option, date);
}
};
$("#to").datepicker(settings);
$("#from").datepicker($.extend({}, settings, { defaultDate: '-30d'}));
See it in action: http://jsfiddle.net/william/xtATL/.
Edit:
You can make use of the utility function $.datepicker.formatDate(format, date, settings)
to format a date to be displayed in the input:
$("#to").val(function() {
return $.datepicker.formatDate('M d, yy', new Date(), settings);
});
$("#from").val(function() {
var thirtyDaysAgo = new Date().getTime() - 30 * (1000*60*60*24);
return $.datepicker.formatDate('M d, yy', new Date(thirtyDaysAgo), settings);
});
See the updated example: http://jsfiddle.net/william/xtATL/4/.
Either set the date in the input (using the correct date format) prior to initialising the datepicker, or use the setDate method if the datepicker after initialisation. E.g.
var d = new Date(); jQuery("#to).datepicker("setDate", d);
精彩评论