Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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..

like image 322
Hansal Mehta Avatar asked Oct 31 '14 04:10

Hansal Mehta


2 Answers

This should do the trick

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

It's 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.

like image 91
akaBase Avatar answered Sep 25 '22 01:09

akaBase


Though, question is answered, for people who just want a date object or set a date with specific format. There is simple functions jQuery provides. Here's working jsfiddle

$( "#datepicker" ).datepicker({ dateFormat: "dd-mm-yy" });

$("#datepicker").datepicker('setDate', '10-03-2020');
                 // pass string of your format or Date() object

$("#datepicker").datepicker('getDate');
                 // returns Date() object

$("#another_datepicker").datepicker('setDate', $("#datepicker").datepicker('getDate'));
                 // pass string of your format or Date() object
like image 21
It's K Avatar answered Sep 24 '22 01:09

It's K