Question

I have a working range selection using the basic Jquery UI date range from the UI website.

HTML

<button id="week">Past Week</button><br />
<label for="from">From</label>
<input type="text" id="from" name="from" value""> 
<label for="to">to</label>
<input type="text" id="to" name="to" value"">

JQ

$( "#from" ).datepicker({
  defaultDate: "+1w",
  dateFormat: 'MM d, yy',
  numberOfMonths: 1,
  onClose: function( selectedDate ) {
    $( "#to" ).datepicker( "option", "minDate", selectedDate );
  }
});
$( "#to" ).datepicker({
  defaultDate: "+1w",
  dateFormat: 'MM d, yy',
  numberOfMonths: 1,
  onClose: function( selectedDate ) {
    $( "#from" ).datepicker( "option", "maxDate", selectedDate );
  }
});

I also need to include a button for automatically selecting the previous 7 days from the current date. I've used the new Date(); method to achieve a 'working' version (no date formating at the moment).

$( "#week" ).click(function() {
  var today = new Date();
  var lastweek = new Date(new Date().setDate(new Date().getDate()-7));
  $( "#from" ).val(lastweek);
  $( "#to" ).val(today);
});

However I'd prefer to use the datepicker function to achieve the previous week range, and I cannot figure out how to achieve that (if its even possible). Primary reason being that if a user chooses the "Prev Week" button option, then selects a new date, I want the existing date to be selected on the calendar widget.

I have this in a jsfiddle http://jsfiddle.net/lopac1029/RuhWj/

Was it helpful?

Solution

Boom boom boom. Another related question was offered to me in the sidebar after posting, and I was able to use that as a basis to figure out this:

$( "#week" ).click(function() {
  var today = new Date();
  var from = new Date(today.getTime());
  from.setDate(from.getDate() - 7);
  $("#to").datepicker("setDate", today);
  $("#from").datepicker("setDate", from);
});

jsfiddle updated

Thanks for always being there for me, stackoverflow.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top