Hansal Mehta Hansal Mehta - 23 days ago 7
Javascript Question

How to get the selected date from jquery datepicker

I am using jquery datepicker to show a calendar.Now as per my requirement i want to get the date selected by the user in my jquery variable which i will use in my application but i am not able to get the date ..
Here is the code for datepciker

<div id="datepicker"></div>


and here i am trying to get the selected code..

$(document).ready(function () {

$("#datepicker").datepicker({
onSelect: function (dateText, inst) {
var date = $(this).val();
alert(date);
}
});

});


But, I am not able to get the date ..Please help me ..Thanks..

Answer

This should do the trick

$(function() {
    $("#datepicker").datepicker();
    $("#datepicker").on("change",function(){
        var selected = $(this).val();
        alert(selected);
    });
});

Its basic but here is a jsfiddle with it alerting the selected date when selected

update to change the date format

$(function() {
    $( "#datepicker" ).datepicker({ dateFormat: "yy-mm-dd" });
    $("#datepicker").on("change",function(){
        var selected = $(this).val();
        alert(selected);
    });
});

jsfiddle

3rd update

$(function() {
    $("#datepicker").datepicker({ 
        dateFormat: "yy-mm-dd", 
        onSelect: function(){
        var selected = $(this).val();
        alert(selected);
        }
    });
});

I have used a little more of the native markup for datepicker ui here try this and see if you get the alert as you are after.

Comments