yossi
yossi

Reputation: 1431

How to get the year from datepicker ui?

I have code which the user choose date .

I need to to get the value year and put it in div.

How can I do that?

jsFissl Demo

many Thx. the code:

<div class="demo">
<p>Date: <input type="text" id="datepicker"></p>
</div>
<div id="Year"></div>

$("#datepicker").datepicker({
        changeMonth: true,
        changeYear: true

    });

       $("#Year").text($("#datepicker").val()); 

I try to use .substring(0, 4)but I don't kno how.

Upvotes: 1

Views: 3859

Answers (3)

az4dan
az4dan

Reputation: 659

This shows the year you wanted to extract.

HTML:

<meta charset="utf-8">
    <div class="demo">
    <p>Date: <input type="text" id="datepicker"></p>
    <button>Show year</button>
</div><!-- End demo -->

JS:

$(function() {
    $("#datepicker").datepicker({
        changeMonth: true,
        changeYear: true
    });

    $("button").click(function() {
        var split = $("#datepicker").val().split('/');
        alert(split[2]);
    });
});​

The split method of String class divides the string and returns as an array.

EDIT: This does everything you wanted. Take a look at the onSelect event.

$(function() {
    $("#datepicker").datepicker({
        changeMonth: true,
        changeYear: true,
        onSelect: function(dateText) { 
            var split = $("#datepicker").val().split('/');
            $("#Year").text(split[2]);
        }
    });
});​

Upvotes: 0

FosterZ
FosterZ

Reputation: 3911

How about this : JSFiddle No need to do string manipulation, just create Date object using selected date from datepicker and use getFullYear() method to get selected year...

$(function() {
    $("#datepicker").datepicker({

       onSelect: function(date) {
        var d = new Date(date);
        alert(d.getFullYear());
       },
       changeMonth: true,
       changeYear: true
    });

});

Upvotes: 0

balexandre
balexandre

Reputation: 75073

You can convert that input value into a Javascript Date as well and have everything from it's method.

http://jsbin.com/ugaxob/2/edit

$(".btn-getdate").click(function() {

  var dt = $("#datepicker").val(),
      d = new Date(dt);    

  $("#Year").text(d.getFullYear());

});

or go wild and use MomentJs plugin and you will get so much fun (live example updated)


When you want to perform something on a plugin, that is called act upon an event, and you should see the Events tab in the DatePicker, where you can find onSelect.

My live example was changed to act upon selection and no need to press any link or button.

Upvotes: 1

Related Questions