Search code examples
javascripthtmldaterangepicker

Pass Date Range to seperate inputs


I am jsut learning JS and have a question about using a date range picker. I want to use this type of selection but how would I go about passing start and end times to the startDate and endDate input boxes?

HIDDEN: <input type="text" class="form-control" name="startDate" id="inlineFormInputGroup" placeholder="Start Date">
HIDDEN: <input type="text" class="form-control" name="endDate" id="inlineFormInputGroup" placeholder="End Date">

SHOWN on PAGE: <input type="text" class="form-control" name="date" id="demo" >

$('#demo').daterangepicker({
    ranges: {
        'Today': [moment(), moment()],
        'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
        'Last 7 Days': [moment().subtract(6, 'days'), moment()],
        'Last 30 Days': [moment().subtract(29, 'days'), moment()],
        'This Month': [moment().startOf('month'), moment().endOf('month')],
        'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
    },
    "startDate": "03/27/2020",
    "endDate": "04/02/2020"
}, 
    );
});

I searched on here but everything pointed to python scripts. This is JS within an HTML page.

Thank you


Solution

  • I was able to get this to work by assigning to inputs in JS using the correct method.

    
      $('input.date_range').daterangepicker({
        autoApply:true,
        ranges: {
           'Today': [moment(), moment()],
           'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
           'Last 7 Days': [moment().subtract(6, 'days'), moment()],
           'Last 30 Days': [moment().subtract(29, 'days'), moment()],
           'This Month': [moment().startOf('month'), moment().endOf('month')],
           'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
       },
    
    
    
       });
    
      $('form').submit(function (ev, picker) {
          [startDate, endDate] = $('.date_range').val().split(' - ');
          $(this).find('input[name="datemin"]').val(startDate);
          $(this).find('input[name="datemax"]').val(endDate);
      });
    
    

    Form

      <form>
    
      <div class="form-row align-items-center">
        <div class="col-auto">
          <input type="hidden" name="datemin">
          <input type="hidden" name="datemax">
          <label class="sr-only" for="inlineFormInput">Select Date Range</label>
          <input type="text" class="form-control mb-2 date_range" id="inlineFormInput" size="30">
        </div>
        <div class="col-auto">
          <button type="submit" class="btn btn-primary mb-2">Submit</button>
        </div>
      </div>
      </form>
    

    https://jsfiddle.net/erkc64ot/5/