Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bootstrap-datepicker empties field after selecting current date

If I have autoclose enabled, and I select the field from the calendar that is already chosen, it empties the field and then closes the datepicker as expected. How can I still have the autoclose feature, but not have it empty the field?

Look at the demo for an example, http://eternicode.github.io/bootstrap-datepicker/?markup=input&format=&weekStart=&startDate=&endDate=&startView=0&minViewMode=0&todayBtn=false&language=en&orientation=auto&multidate=&multidateSeparator=&autoclose=on&keyboardNavigation=on&forceParse=on#sandbox

  1. Make sure autoclose is on
  2. Select a date.
  3. open the datepicker again, select the currently selected date again.
  4. field is empty again

Thanks

like image 930
NeedACar Avatar asked Jul 27 '14 12:07

NeedACar


2 Answers

Bootstrap Datepicker provides events that you can leverage to accomplish your goal.

Here's one way to do it:

$('#sandbox-container input').datepicker({
    autoclose: true
});

$('#sandbox-container input').on('show', function(e){
    if ( e.date ) {
         $(this).data('stickyDate', e.date);
    }
    else {
         $(this).data('stickyDate', null);
    }
});

$('#sandbox-container input').on('hide', function(e){
    var stickyDate = $(this).data('stickyDate');

    if ( !e.date && stickyDate ) {
        $(this).datepicker('setDate', stickyDate);
        $(this).data('stickyDate', null);
    }
});

Not necessarily the most elegant, but as you can see here, it does the trick:

http://jsfiddle.net/klenwell/LcqM7/ (tested in Chrome)

like image 78
klenwell Avatar answered Sep 21 '22 14:09

klenwell


This seems to be most generic solution as there was issue when we click on input text and click on some other component on webpage apart from date selection:

//Date picker 
$('#datepickerInputId').datepicker({
    autoclose : true,
}).on('show', function(e){
    if ( e.date ) {
        $(this).data('stickyDate', e.date);
    } else if($(this).val()){
        /**auto-populate existing selection*/
        $(this).data('stickyDate', new Date($(this).val()));
        $(this).datepicker('setDate', new Date($(this).val()));
    } else {
        $(this).data('stickyDate', null);
    }
}).on('hide', function(e){
    var stickyDate = $(this).data('stickyDate');
    if ( !e.date && stickyDate ) {
        $(this).datepicker('setDate', stickyDate);
        $(this).data('stickyDate', null);
    }
});

kindly suggest if any modification needed

like image 44
PankajChandankar Avatar answered Sep 21 '22 14:09

PankajChandankar