簡體   English   中英

如何從 jQuery UI datepicker 獲取日期

[英]How to get the date from jQuery UI datepicker

每當用戶在 jQuery UI datepicker 中選擇日期並單擊表單上的按鈕時,我都想從 datepicker 獲取日期。

好吧,我需要獲得他們選擇的日期的日、月和年。 如何獲取日期表單 jQuery UI?

使用

var jsDate = $('#your_datepicker_id').datepicker('getDate');
if (jsDate !== null) { // if any date selected in datepicker
    jsDate instanceof Date; // -> true
    jsDate.getDate();
    jsDate.getMonth();
    jsDate.getFullYear();
}

您可以使用 getDate 函數檢索日期:

$("#datepicker").datepicker( 'getDate' );

該值作為 JavaScript 日期對象返回。

如果要在用戶選擇日期時使用此值,可以使用 onSelect 事件:

$("#datepicker").datepicker({
   onSelect: function(dateText, inst) { 
      var dateAsString = dateText; //the first parameter of this function
      var dateAsObject = $(this).datepicker( 'getDate' ); //the getDate method
   }
});

在這種情況下,第一個參數是所選日期作為字符串。 使用 parseDate 將其轉換為 JS 日期對象。

有關完整的 jQuery UI DatePicker 參考,請參閱http://docs.jquery.com/UI/Datepicker

試試這個,就像魅力一樣,給出你選擇的日期。 onsubmit 表單嘗試獲取此值:-

var date = $("#scheduleDate").datepicker({ dateFormat: 'dd,MM,yyyy' }).val();

參考這里

getdate 的鏈接: https : //api.jqueryui.com/datepicker/#method-getDate

$("#datepicker").datepicker( 'getDate' );

有時會遇到很多麻煩。 在 datapicker 數據的屬性值為 28-06-2014,但 datepicker 是 show 或 today 或沒有。 我是這樣決定的:

<input type="text" class="form-control datepicker" data-value="<?= date('d-m-Y', (!$event->date ? time() : $event->date)) ?>" value="<?= date('d-m-Y', (!$event->date ? time() : $event->date)) ?>" />

我添加到 datapicker 屬性數據值的輸入,因為如果調用jQuery(this).val() OR jQuery(this).attr('value') - 沒有任何效果。 我決定循環初始化每個數據選擇器並從屬性數據值中獲取其值:

 $("form .datepicker").each(function() {
        var time = jQuery(this).data('value');
        time = time.split('-');
        $(this).datepicker('setDate', new Date(time[2], time[1], time[0], 0, 0, 0));
    });

它工作正常 =)

NamingException 的答案對我有用。 除了我用

var date = $("#date").dtpicker({ dateFormat: 'dd,MM,yyyy' }).val()

datepicker沒有工作,但dtpicker做到了。

我只是做了一些網頁抓取來發現 JequeryUI datepicker 的行為,這對我來說是必要的,因為我不熟悉 JS 對象,所以:

var month = $(".ui-datepicker-current-day").attr("data-month");
var year = $(".ui-datepicker-current-day").attr("data-year");
var day = $(".ui-state-active").text();

它只是選擇與類更改相關的值,因此您可以實現 onchange 事件:

$(document).on('change', '#datepicker', function() { 
    var month = $(".ui-datepicker-current-day").attr("data-month");
    var year = $(".ui-datepicker-current-day").attr("data-year");
    var day= $(".ui-state-active").text();
   $("#chosenday").text( day + " " + month  + " " + year )  ;
                        
});

或檢查是否選擇了當前日期:

   if( $("a").hasClass("ui-state-active") ){ 
     var month = $(".ui-datepicker-current-day").attr("data-month");
     var year = $(".ui-datepicker-current-day").attr("data-year");
     var day= $(".ui-state-active").text();
     $("#chosenday").text( day + " " + month  + " " + year );
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM