Jaco
Jaco

Reputation: 1694

jQuery: Add months to Datepicker

With the help of jQuery and Datepicker, I would like to add # of months to Today's Date.

My attempts below produce unexpected results:

e.g. If I add 0 months, I get 9 months addition to Today's date If I add 1 month, I get 10 months addition.

I have stepped through the code and it seems the error is something with formatting. If I hardcode:

var ten = $('#mthschange').val();

with

var ten = 12;

it works fine

if I test:

var ten = $('#mthschange').val();
alert(ten);

it will alert me: 12 (if I put in 12).

it seems to be related to data types.

How do I correctly instruct Datepicker to add months to a date?

$(function() {
  $('#mthschange').change(function() {
    var ten = $('#mthschange').val();
    var d = new Date();
    d.setMonth(d.getMonth() + ten);
    var e = ($.datepicker.formatDate('yy-mm-dd', d));
    $("#res").val(e);
  });
});
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Datepicker - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<p>Input Field : <input id="mthschange" type="text"></p>
<p>Output Field : <input id="res" type="text"></p>
</body>
</html>

Upvotes: 0

Views: 445

Answers (1)

Nick
Nick

Reputation: 147146

Your problem is that ten is a string, not an integer, so when you execute

d.getMonth() + ten

you get something like 112 instead of 13. Change

var ten = $('#mthschange').val();

to

var ten = parseInt($('#mthschange').val());

and the code works fine:

$(function() {
  $('#mthschange').change(function() {
    var ten = parseInt($('#mthschange').val());
    var d = new Date();
    d.setMonth(d.getMonth() + ten);
    var e = ($.datepicker.formatDate('yy-mm-dd', d));
    $("#res").val(e);
  });
});
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Datepicker - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<p>Input Field : <input id="mthschange" type="text"></p>
<p>Output Field : <input id="res" type="text"></p>
</body>
</html>

Upvotes: 3

Related Questions