Was using Bootstrap DateRangePicker Jquery plugin, and to help deal with manual entry issues, I made the date field readonly and used created ranges to it, from which the user should pick the one they want. Something like this..
// set datepicker
function cb(start, end) {
$('#daterange input').val(start.format('Do MMM YYYY') + ' - ' + end.format('Do MMM YYYY'));
}
$('#daterange').daterangepicker({
autoApply: true,
autoUpdateInput:true,
ranges: [
'Today': [moment(), moment()],
'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
'This Week': [moment().startOf('week'), moment()],
'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')]
}
}, cb);
The problem is, how do I clear the contents of the field, given that it is readonly and no button to do that exists on the interface of the datepicker?
On the official website of dararange picker, they somehow provide a slight solution, which is that when the 'Cancel' button is clicked you can attach an event that clears the date field.
$('#daterange').daterangepicker({
locale: { cancelLabel: 'Clear' }
});
$('#daterange').on('cancel.daterangepicker', function(ev, picker) {
//do something, like clearing an input
$('#daterange').val('');
});
But that is not what I intend to do. Both Clear and Cancel and valid actions. So now, how do I go about it?
This is how I did it:I added a range called "None" at the top of the existing ranges, which when clicked clears the field. The values passed to the range are two null values, and on the cb
function (or whatever function you use to manipulate the field) I check to see if the date passed is valid, failure to which I clear the field (Not Valid means Null was passed, or "None" was clicked.).
<script>
// set datepicker
function cb(start, end) {
if(start._isValid && end._isValid)
{
$('#daterange input').val(start.format('Do MMM YYYY') + ' - ' + end.format('Do MMM YYYY'));
}
else
{
$('#daterange input').val('');
}
}
$('#daterange').daterangepicker({
autoApply: true,
autoUpdateInput:true,
ranges: {
'None': [null,null],
'Today': [moment(), moment()],
'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
'This Week': [moment().startOf('week'), moment()],
'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')]
}
}, cb);
</script>