How can I change my API link with a date picker - javascript

Currently my api link is dynamic by selecting the current year and month.
Example:
APILINK.../202109
That part is fine... But what I want to do is change the last part of the API link (Year and Month) with a datepicker and I'm not sure how I can do that.
My current Code:
const timehsheetUrl = "API LINK"
const today = new Date();
const date = today.getFullYear()+('0' + (today.getMonth() + 1)).slice(-2);
const settings = {
"async": true,
"crossDomain": true,
"url": timesleetUrl + date,
"method": "GET",
"headers": {}
}

No, you don't need to use datepicker plugin, while plugin is more convenient.
Here's an example with default HTML date-input.
const timesleetUrl = "API LINK";
const today = new Date();
function urlDateSuffix(_date) {
return _date.getFullYear()+('0' + (_date.getMonth() + 1)).slice(-2);
}
let settings = {
"async": true,
"crossDomain": true,
"url": timesleetUrl + urlDateSuffix(today),
"method": "GET",
"headers": {}
}
console.log(settings);
$(function() {
$('#datepicker').change(function() {
settings.url = timesleetUrl + urlDateSuffix(new Date(this.value));
console.log(settings);
alert(settings.url);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="date" id="datepicker">

It's easy use jQuery date picker.
On date select script should return selected date's month and year.
Store the output in variable and format. The code shown below will help you
// html markup, use jQuery UI CDN in head section
<input type="text" id="calendar" name="date1"/>
// html markup
<script>
$('#calendar').datepicker({
dateFormat: 'yy-m-d',
inline: true,
onSelect: function(dateText, inst) {
var date = $(this).datepicker('getDate'),
day = date.getDate(),
month = date.getMonth() + 1,
year = date.getFullYear();
// alert(day + '-' + month + '-' + year);
// this is your result
alert( "api link is "+"APILINK.../"+year+month);
}
});
</script>

Related

How to update a Jquery calendar with a JS variable

I am trying to implement this jQuery Calendar into my website. I've got the calendar running, and everything works.
I want to be able to alter the date in the calendar when a user pushes one of four buttons:
1 hour
Tomorrow
1 week
2 weeks
When a user pushes a button I would like the calendar to change the date accordingly. The calendar has the option called startDate that I can use for the purpose - but I can't seem to trigger it.
The content of val = f.x. 2020-03-07 10:02
$.datetimepicker.setLocale('da');
$('#datetimepicker').datetimepicker({
dayOfWeekStart: 1,
lang: 'da',
inline: true,
scrollMonth: false,
timepicker: false,
startDate: new Date(document.getElementById('timeForAlert').value),
onSelectDate: function() {
userHasChosen();
},
onSelectTime: function() {
userHasChosen();
}
});
$('#datetimepicker4').datetimepicker({
format: 'Y-d-m'
});
$('.some_class').datetimepicker();
function makeReadable(val) {
var mydate = new Date(val);
var hour = document.getElementById('hour').value;
var minute = document.getElementById('minutes').value;
var str = mydate.getFullYear() + '-' + ("0" + (mydate.getMonth() + 1)).slice(-2) + '-' + ("0" + mydate.getDate()).slice(-2) + ' ' + hour + ':' + minute + ':00';
return str;
}
function oneday(val) {
document.getElementById('datetimepicker').value = val;
document.getElementById('timeForAlert').value = makeReadable(val);
$.datetimepicker();
stopReload();
}
Found the solution asking in another forum.
The documentation for this script is terrible !
Here is what we found:
$(function() {
$('#dt').datetimepicker({
dayOfWeekStart: 1,
lang: 'da',
inline: true,
scrollMonth: false,
timepicker: false,
startDate: new Date()
});
});
$('#btn').click(function() {
$('#dt').datetimepicker({
value: new Date('2020-01-01T00:00:00Z')
});
});
Run this from a button with id = btn and you're set

Why my jQuery script executes just once?

I have a problem with my jQuery UI datepicker. I have this code :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script>
<script>
jQuery(document).ready(function($) {
$('#datepickerFrom').datepicker({
dateFormat: 'yy-m-d',
inline: true,
onSelect: function(dateText, inst) {
var date = $(this).datepicker('getDate'),
day = date.getDate(),
month = date.getMonth() + 1,
year = date.getFullYear();
var url = $('#reservation').attr('href');
url = url.replace('05&', day + '&');
$('#reservation').attr('href', url);
var url2 = $('#reservation').attr('href');
url2 = url2.replace('12', month);
$('#reservation').attr('href', url2);
var url3 = $('#reservation').attr('href');
url3 = url3.replace('2016', year);
$('#reservation').attr('href', url3);
}
});
$('#datepickerTo').datepicker({
dateFormat: 'yy-m-d',
inline: true,
onSelect: function(dateText, inst) {
var date = $(this).datepicker('getDate'),
day = date.getDate(),
month = date.getMonth() + 1,
year = date.getFullYear();
var url4 = $('#reservation').attr('href');
url4 = url4.replace('=2016', '=' + year);
$('#reservation').attr('href', url4);
var url5 = $('#reservation').attr('href');
url5 = url5.replace('13', +month);
$('#reservation').attr('href', url5);
var url6 = $('#reservation').attr('href');
url6 = url6.replace('09', day);
$('#reservation').attr('href', url6);
}
});
});
</script>
<p>Date arrivée :
<input type="text" id="datepickerFrom">
</p>
<p>Date départ :
<input type="text" id="datepickerTo">
</p>
<a id="reservation" class="et_pb_button et_pb_button_0 et_pb_module et_pb_bg_layout_light" href="https://mywebsite.com/book?shs&chkin=2016-12-05&chkout=2016-13-09&step=1">Réservez</a>
When I click on a date (datepickerTo and datepickerFrom), it updates my href link but only one time. When I change the date, the script is not executed.
Works only at the first time since you search for the inital values and replace them. Check this code of yours:
var url = $('#reservation').attr('href');
url = url.replace('05&', day + '&');
$('#reservation').attr('href', url);
var url2 = $('#reservation').attr('href');
url2 = url2.replace('12', month);
$('#reservation').attr('href', url2);
var url3 = $('#reservation').attr('href');
url3 = url3.replace('2016', year);
$('#reservation').attr('href', url3);
It basically replaces '05' what the given day, '12' with the given month and '2016' with the given year. When the user chooses a different date this code finds nothing to replace with this new date.

How to get date in specific format

I want to have the dateformat in this format: 2015-08-04T00:00:00Z.
so first year, month, day.
beforeShowDay: function (date) {
var dt = $.datepicker.formatDate('yy-mm-dd', date, "getDate")
return [$('#form_one3 > option:gt(0)[value="' + dt + 'T00:00:00Z"]').length != 0];
},
onSelect: function (dateText, inst) {
var dt = $.datepicker.formatDate('yy-mm-dd', dateText, "getDate")
alert(dt);
var hallo = $("#form_inp1").val() + 'T00:00:00Z';
alert(dateText);
alert(hallo);
//$("#form_inp1").datepicker("getDate");
//alert($("#form_inp1").formatDate('yy-mm-dd', dateText, "getDate")
},
But If I do an alert(dateText) I see the format as: 4-8-2015 and it has to be: 2015-08-04.
Thank you
If I try it like this:
onSelect: function (dateText, inst) {
dateText = dateText.split("-");
dateText = new Date('' + dateText[2] + '-' + dateText[1] + '-' + dateText[0] + '');
alert(dateText);
}
I get invalid date
So this var hallo = $("#form_inp1").val() + 'T00:00:00Z';
returns: 4-8-2015T00:00:00Z . But it has to be:2015-08-04T00:00:00Z.
Thank you
Quick fix is to change the date format using plain Javascript. This can be achieved by following script.
dt= dt.split("-");
dt = new Date('' + dt[2] + '-' + dt[1] + '-' + dt[0] + '');
to add zero in case the day, month and year is below 10, use following method.
function AddTrailingZero(i) {
if (i < 10) { i = "0" + i }; // add zero in front of numbers < 10
return i;
}
Let me know if you have any question related to the code snippet above.

jquery datepicker beforeShowDay works for wrong month?

I'm using jquery's datepicker to select dates and I want to highlight some dates - but I'm experiencing a strange problem with beforeShowDay.
When the page loads it seems that the json data is loaded, but when I click into the input box and datepicker appears, nothing is highlighted. After I click on forward month or backward, data from a previous month is loaded (e.g. click in input -> datepicker appears -> no highlights -> click on next month -> data from prev month appears highlighted)...
I've googled a long time now, checked if data is loaded before everything, but somehow this behaviour is not changing. Both datepicker experience the same problem.
(jquery-ui datepicker 1.10.1, jquery 1.9.1)
I'm glad about every hint!
var resDates;
var done = false;
function markDate(date) {
var ret = [true, 'free'];
if (!done) {
$.ajax({
dataType: "json",
url: "modules/OutShop/getReservations.php",
data: {item_id: $("#item-id").val()},
async: false,
success: function (dates) {
resDates = dates;
done = true;
}
});
}
$.each(resDates, function(key, value) {
var d = (date.getFullYear() + "-" + ("0" + date.getMonth()).slice(-2) + "-" + ("0" + date.getDate()).slice(-2));
if (d == value["day"]) {
//$("body").append("d: " + d + ", v: " + value["day"] + ", s: " + value["status"] + " ");
//$("body").append("s: " + value["status"] + " ");
if (value["status"] == "1")
ret = [false, 'marked'];
else if (value["status"] == "2")
ret = [false, 'reserved'];
else
ret = [true, 'free'];
}
});
return ret;
}
$(document).ready(function() {
if (!done) {
$.ajax({
dataType: "json",
url: "modules/OutShop/getReservations.php",
data: {item_id: $("#item-id").val()},
async: false,
success: function (dates) {
resDates = dates;
//done = true;
}
});
}
$("#item-datepicker-min").datepicker({
showButtonPanel: true,
defaultDate: +3,
minDate: +3,
beforeShowDay: markDate,
onSelect: function(selectedDate) {
$("#item-datepicker-max").datepicker("option", "minDate", selectedDate);
}
});
$("#item-datepicker-max").datepicker({
showButtonPanel: true,
minDate: +3,
defaultDate: +6,
beforeShowDay: markDate,
onSelect: function(selectedDate) {
$("#item-datepicker-min").datepicker("option", "maxDate", selectedDate);
}
});
});
EDIT
For further information: This is an example json object I got from the ajax response.
[{"status":3,"day":"2013-04-10"},{"status":3,"day":"2013-04-11"},{"status":3,"day":"2013-04-12"},{"status":3,"day":"2013-04-13"},{"status":2,"day":"2013-04-10"},{"status":2,"day":"2013-04-11"},{"status":2,"day":"2013-04-12"},{"status":2,"day":"2013-04-13"}]
Looks like your months are offset by 1, the javascript method date.getMonth() returns the months zero-based (eg. January is 0, Feb is 1) and your PHP script returns the date in normal format (Jan is 1, Feb is 2)
Check this
So if you change
var d = (date.getFullYear() + "-" + ("0" + date.getMonth()).slice(-2) + "-" + ("0" + date.getDate()).slice(-2));
to
var d = (date.getFullYear() + "-" + ("0" + date.getMonth()+1).slice(-2) + "-" + ("0" + date.getDate()).slice(-2));
you should get the right month showing

Unexpected Identifier Syntax Error in Javascript

I get an Unxepected Identifier editor with the following code. I've been troubleshooting it all day, and nothing. Hoping a fresh pair of eyes can spot my error. I'm trying to use jQuery UI to set up a date-picker and then get and manipulate the date. Changing the date on the picker should change an image on the page associated with that date via ajax.
$(document).ready(function(){
// Datepicker
$('#datepicker').datepicker({
dateFormat: 'yy-mm-dd',
inline: true,
minDate: new Date(2012, 06 - 1, 1),
maxDate:new Date(2012, 09 - 1, 31),
onSelect: function(){
var day1 = ($("#datepicker").datepicker('getDate').getDate()).toString().replace(/(^.$)/,"0$1");
var month1 = ($("#datepicker").datepicker('getDate').getMonth() + 1).toString().replace(/(^.$)/,"0$1");
var year1 = $("#datepicker").datepicker('getDate').getFullYear();
var fullDate = year1 + "/" + month1 + "/" + day1;
var dashDate = year1 + "-" + month1 + "-" + day1;
var str_output = "<a id=\"single_image\" href=\"http://www.lasalle.edu/150/dayinhistory/" + fullDate + ".jpg\" title=\"\"><img src=\"http://www.lasalle.edu/scripts/timthumb/timthumb.php?src=http://www.lasalle.edu/150/dayinhistory/" + fullDate + ".jpg&w=560&h=350&zc=1&a=t\">";
$('#this-day-photo-archive').html(str_output);
var data = 'day=' + dashDate;
$.ajax({
url: 'http://www.lasalle.edu/150/content/day_grab.php',
type: "GET",
data: data,
cache: false,
success: function(html) {
$('#this-day-info').html(html);
console.log (html);
$(".left").click(function() {
$('#datepicker').datepicker( "setDate" , -1d );
});
$(".right").click(function() {
$('#datepicker').datepicker( "setDate" , +1d );
});
}
});
}
});
});
You should replace
$('#datepicker').datepicker( "setDate" , -1d );
with
$('#datepicker').datepicker( "setDate" , "-1d" );
(and the same for +1d)
A link to some examples for confirmation

Categories