0

I am trying to follow the below code to implement addition of days to datepicker

[https://jsfiddle.net/up82wt76/][1]

Below is the code I implemented in Visual Studio 2022

It is a straight copy. Why it does not work?

Any help would be greatly appreciated.

$('.pickupDate').datepicker();
$('.dropoffDate').datepicker();

$('.pickupDate').change(function() {
  var date2 = $('.pickupDate').datepicker('getDate', '+1d');
  //date2.setDate(date2.getDate()+1); 
  $('.dropoffDate').datepicker('setDate', date2.getDate() + 1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

<div>
  <br />
  <br />
  <input type="text" class="pickupDate" />
  <input type="text" class="dropoffDate" />
</div>

2
  • Open up the developer tools (<kbd>F12</kbd>) you'll likely see an error message in the console, or a failed request in the Network tab. You can also use the debugger to diagnose exactly where the script is failing. But in your JSFiddle link you shared, it seems to be working fine, so I'm not sure what the issue is. Commented Sep 10, 2022 at 21:49
  • You need to load the scripts before you can use them. Either surround your code in $( document ).ready(function() {...}); or load the dependencies before executing your code. Commented Sep 10, 2022 at 21:51

1 Answer 1

1

Looks like the DOM hasn't finished loading at the time that you're executing your JavaScript.

jQuery has an implementation of the window load event, which is $( document ).ready().

In your example, that would be:

$(document).ready(() => {
  $('.pickupDate').datepicker();
  $('.dropoffDate').datepicker();
  $('.pickupDate').change(() => {
    const date2 = $('.pickupDate').datepicker('getDate', '+1d');
    $('.dropoffDate').datepicker('setDate', date2.getDate() + 1);
  });
});

Also, you probably want to load those external scripts from within your <head> tag. You could also consider downloading them locally using NPM.

3
  • Your answer perfectly works. But I need to change little bit. If I change the input type of text control to Date, then it does not work. How to resolve that?
    – CPK_2011
    Commented Sep 10, 2022 at 21:59
  • The problem is I want to scroll through the Year easily instead of scrolling through each month backwards or forwards.
    – CPK_2011
    Commented Sep 10, 2022 at 22:25
  • Heya @CPK_2011, glad you've got the first bit working :) The second part (scrolling through the month / year backwards) sounds like a separate question, so accept an answer here, then post a new question, and I'll try and help Commented Sep 11, 2022 at 11:16

Not the answer you're looking for? Browse other questions tagged or ask your own question.