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" />
<input type="text" />
</div>
CodePudding user response:
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.