JQuery Datepicker: запретить закрытие выбора при нажатии на дату

Привет друг другу stackoverflow: ers,

Я использую плагин jQuery Datepicker вместе с Мартин Милесич Timepicker. Все отлично работает, за исключением того факта, что нажатие даты в datepicker закрывает виджет, не оставляя времени, чтобы выбрать время.

Вопрос: Поэтому мне интересно, есть ли способ предотвратить закрытие виджета при нажатии на дату и вместо этого заставить пользователей нажать кнопку "Готово" (которая появляется при включении опции showButtonPanel: true), или щелчок за пределами виджета. Я не хочу, чтобы мои пользователи дважды открывали виджет! См. Поведение онлайн в демоверсии timepicker

Любая помощь в решении этой проблемы или даже указатели в правильном направлении оценивается!

Дополнительная информация: Я использую файлы, поставляемые из ссылки загрузки Martins: http://milesich.com/tpdemo/timepicker-0.2.0.zip

  • JQuery-UI-1.7.2.custom.min.js
  • timepicker.js(последняя версия 0.2.0)

Это параметры, которые я использую:

$(document).ready(function(){
    $(".datepicker").datepicker({
        duration: '',  
        showTime: true,  
        constrainInput: false,  
        stepMinutes: 5,  
        stepHours: 1, 
        time24h: true,
        dateFormat: "yy-mm-dd",
        buttonImage: '/static/images/datepicker.png',
        buttonImageOnly: true,
        firstDay: 1,
        monthNames: ['Januari','Februari','Mars','April','Maj','Juni','Juli','Augusti','September','Oktober','November','December'],
        showOn: 'both',
        showButtonPanel: true
     });
})

Ответы

Ответ 1

вместо того, чтобы изменять источник, лучше всего использовать существующие события

onSelect: function() {
    $(this).data('datepicker').inline = true;                               
},
onClose: function() {
    $(this).data('datepicker').inline = false;
}

Ответ 2

Для справки, и так как люди спрашивали меня об этом через почту. Здесь фрагмент кода, который нужно добавить в timepicker.js:

/**
 * Don't hide the date picker when clicking a date
 */
$.datepicker._selectDateOverload = $.datepicker._selectDate;
$.datepicker._selectDate = function(id, dateStr) {
    var target = $(id);
    var inst = this._getInst(target[0]);
    inst.inline = true;
    $.datepicker._selectDateOverload(id, dateStr);
    inst.inline = false;
    this._updateDatepicker(inst);
}

Удачи вам в работе с вашим сайтом!

Ответ 3

Вам придется взломать дампинг самостоятельно. Это код, который он использует. Если он не встроен, он будет скрываться при выборе даты.

Вы можете передать свой собственный метод onSelect и быстро изменить экземпляр datePicker, чтобы он был встроен, а затем изменить его, не изменяя внутренние элементы datepicker, но это очень хакерское решение.

if (inst.inline)
        this._updateDatepicker(inst);
else {
      this._hideDatepicker(null, this._get(inst, 'duration'));
      this._lastInput = inst.input[0];
      if (typeof(inst.input[0]) != 'object')
      inst.input[0].focus(); // restore focus
      this._lastInput = null;
}

Ответ 4

Вот решение:

onSelect: function ( dateText, inst ) {
    ..... // Your code like $(this).val( dateText );`


    //Set inline to true to force "no close"
    inst.inline = true;
},
onClose: function(date,inst){
    //Set inline to false => datapicker is closed
    // onClose is called only if you click outside the datapicker, onSelect will not
    // trig onClose due to inline = true
   inst.inline = false;
}

`

Ответ 5

Почему все комментарии обеспечивают обход? это straigtfwordword:

Использовать встроенный календарь с помощью altField:)

    <input type="text" id="alternate" size="30" />
    <div id="datepicker"></div>

    <script>
       $("#datepicker").datepicker({
          altField: "#alternate"
       });
    </script>

проверить эту скрипту: http://jsfiddle.net/menocomp/y2s662b0/1/

Ответ 6

Следуя тому, что предложил Эмиль, я нашел более удобный и простой способ изменить виджет, чтобы поддерживать не закрывающий виджет на выбранном событии.

Во-первых, я добавил другое свойство в dict по умолчанию для виджета:

closeOnSelect:true //True to close the widget when you select a date

Во-вторых, найдите этот оператор в методе _selectDate:

if (inst.inline)
        this._updateDatepicker(inst);
else {
        ...
    }

И измените условие следующим образом:

var closeOnSelect = this._get(inst, "closeOnSelect");        
if (inst.inline || !closeOnSelect)
        this._updateDatepicker(inst);
else {
        ...
    }

Попробуй, он работает для меня. Я сделал это над версией JQuery UI 1.8.5.

Ответ 7

Если вы используете jquery-ui-1.8.5.custom.min.js и jquery-ui.multidatespicker.js, вы можете изменить jquery-ui-1.8.5.custom.min.js: из:

if(a.inline)this._updateDatepicker(a);

в

if(a.inline || !this._get(a, 'closeOnSelect'))this._updateDatepicker(a);

Ответ 8

хорошо это грязное обходное решение... но оно работает для меня... даже с showButtonPanel: true

  $(function() {
    var dp_c = null, dp_once = false;
    $( '#datepicker' ).datepicker({
      showButtonPanel: true,
      onSelect: function() {
        $(this).data('datepicker').inline = true;  
        setTimeout(function () {
          $('#ui-datepicker-div').find('.ui-datepicker-buttonpane').append(dp_c);
        }, 1);

      },
      onClose: function() {
        $(this).data('datepicker').inline = false;
      }
    }).click(function () {
      if(!dp_once) {
        setTimeout(function () {
          dp_c = $('#ui-datepicker-div').find('.ui-datepicker-close').clone();
        }, 500);
        dp_once = !!1;
      }
    });

    $('#ui-datepicker-div').on('click', '.ui-datepicker-close', function () {
      $('#datepicker').datepicker( "hide" );
    });

  });

Ответ 9

Вы должны переопределить встроенную функцию js:

 /* Update the input field with the selected date. */
        _selectDate: function(id, dateStr) {
            var target = $(id);
            var inst = this._getInst(target[0]);
            dateStr = (dateStr != null ? dateStr : this._formatDate(inst));
            if (inst.input)
                inst.input.val(dateStr);
            this._updateAlternate(inst);
            var onSelect = this._get(inst, 'onSelect');
            if (onSelect)
                onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]);  // trigger custom callback
            else if (inst.input)
                inst.input.trigger('change'); // fire the change event
            if (inst.inline)
                this._updateDatepicker(inst);
            else {
                if(inst.settings.hideOnSelect != false){
                    this._hideDatepicker();
                }
                this._lastInput = inst.input[0];
                if (typeof(inst.input[0]) != 'object')
                    inst.input.focus(); // restore focus
                this._lastInput = null;
            }
        },

И добавьте соответствующий параметр в конфигурацию datepicker, например:

var defaultDatePickerOptions = {
        hideOnSelect: false,
        ...
    }; 
 var birthDate = jQuery.extend({}, defaultDatePickerOptions);
 $('#birthdate').datepicker(birthDate);