Loy Bearna
Loy Bearna

Reputation: 17

How to add days to date using jQuery

I have input text like below:

$('#term').change(function() {
  var ll = $(this).val();
  var bb = $('#date').val();
  var date = new Date(bb);
  var newDate = new Date(date);
  newDate.setDate(newDate.getDate() + parseInt(ll));
  var dd = newDate.getDate();
  var mm = newDate.getMonth() + 1;
  var y = newDate.getFullYear();
  var someFormattedDate = dd + '-' + mm + '-' + y;
  $('#due_date').val(someFormattedDate);
});
div {
  margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
  <label for="date">Date:</label>
  <input id="invodate" type="text" id="date" class="form-control" name="date" value="" style="width: 150px;">
</div>
<div class="form-group">
  <label for="term">Term:</label>
  <input type="text" class="form-control" id="term" name="term" value="" style="width: 50px;">
</div>
<div class="form-group">
  <label for="due_date">Due Date:</label>
  <input type="text" class="form-control" id="due_date" name="due_date" value="" style="width: 150px;">
</div>

I wanna give days to input #term and then on Due Date in input show date, but in my code show NaN-NaN-NaN only. What error with my code. thank for answer.

Upvotes: 0

Views: 7506

Answers (2)

adeneo
adeneo

Reputation: 318342

Your first input has two ID's, which is invalid, and you're passing a date object to the Date constructor.

This is quite simple with plain javascript

$('#term').change(function() {
  var ll = $(this).val();
  var bb = $('#date').val();
  var date = new Date(bb);

  date.setDate(date.getDate() + (+ll));

  var dd = date.getDate();
  var mm = date.getMonth() + 1;
  var y = date.getFullYear();
  var someFormattedDate = dd + '-' + mm + '-' + y;

  $('#due_date').val(someFormattedDate);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
  <label for="date">Date:</label>
  <input type="text" id="date" class="form-control" name="date" value="05-05-2017" style="width: 150px;">
</div>
<div class="form-group">
  <label for="term">Term:</label>
  <input type="text" class="form-control" id="term" name="term" value="" placeholder="type here" style="width: 50px;">
</div>
<div class="form-group">
  <label for="due_date">Due Date:</label>
  <input type="text" class="form-control" id="due_date" name="due_date" value="" style="width: 150px;">
</div>

Upvotes: 3

user2102266
user2102266

Reputation: 539

Nan (Not a number) getDate function does not return integer. Object + 11 is not a valid operation (most of the time!).

You can use Datejs mentioned here

var duedate = new Date.today().addDays(11); 

Upvotes: -1

Related Questions