Get the value of bootstrap Datetimepicker in JavaS

2019-01-08 21:38发布

I need to get the value of Datetimepicker in my JavaScript function. I have made something like this, but it doesn't work:

$("#date").click( function(){
    alert(document.getElementById('datetimepicker1').value);
});

It gives me 'undefined'

8条回答
何必那么认真
2楼-- · 2019-01-08 22:13

Or try $("#datetimepicker").data().date;

查看更多
甜甜的少女心
3楼-- · 2019-01-08 22:23

Either use:

$("#datetimepicker1").data("datetimepicker").getDate();

Or (from looking at the page source):

$("#datetimepicker1").find("input").val();

The returned value will be a Date (for the first example above), so you need to format it yourself:

var date = $("#datetimepicker1").data("datetimepicker").getDate(),
    formatted = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours + ":" + date.getMinutes() + ":" + date.getSeconds();
alert(formatted);

Also, you could just set the format as an attribute:

<div id="datetimepicker1" class="date">
    <input data-format="yyyy-MM-dd hh:mm:ss" type="text"></input>
</div>

and you could use the $("#datetimepicker1").find("input").val();

查看更多
做自己的国王
4楼-- · 2019-01-08 22:25

I'm using the latest Bootstrap 3 DateTime Picker (http://eonasdan.github.io/bootstrap-datetimepicker/)

This is how you should use DateTime Picker inline:

var selectedDate = $("#datetimepicker").find(".active").data("day");

The above returned: 03/23/2017

查看更多
兄弟一词,经得起流年.
5楼-- · 2019-01-08 22:29

It seems the doc evolved.

One should now use : $("#datetimepicker1").data("DateTimePicker").date().

NB : Doing so return a Moment object, not a Date object

查看更多
来,给爷笑一个
6楼-- · 2019-01-08 22:29

To call the Bootstrap-datetimepikcer supported functions, you should use the syntax:

$('#datetimepicker').data("DateTimePicker").FUNCTION()

So you can try the function:

$('#datetimepicker').data("DateTimePicker").date();

Documentation: http://eonasdan.github.io/bootstrap-datetimepicker/Functions/

查看更多
Lonely孤独者°
7楼-- · 2019-01-08 22:30

Since the return value has changed, $("#datetimepicker1").data("DateTimePicker").date() actually returns a moment object as Alexandre Bourlier stated:

It seems the doc evolved.

One should now use : $("#datetimepicker1").data("DateTimePicker").date().

NB : Doing so return a Moment object, not a Date object

Therefore, we must use .toDate() to change this statement to a date as such:

$("#datetimepicker1").data("DateTimePicker").date().toDate();

查看更多
登录 后发表回答