how can i apply if loop in datepicker - javascript

i have two date fields, if a user selects only one date then function A should get executed, else if both date are selected then function A and B should get executed. I am using jquery datepicker
These are my two onselect functions:
$(function () {
$("#SelectA").datepicker({
onSelect: function (date) {
A = $('#SelectA').val();
Method(A, "", "");
}
});
});
$(function () {
$("#SelectB").datepicker({
onSelect: function (date) {
A = $('#SelectA').val();
B = $('#SelectB').val();
Method(A, B, "");
}
});
});
The question is that how do i implement IF loop in here? And do i need to terminate functionA and re-invoke it when function B is selected?
function Method(A,B,C) {
$.ajax({
type: "POST",
url: "Services/MethodName.asmx/Method",
data: JSON.stringify({ A: A, B: B, C: C }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
place the data into a table
}
});
}
This is my datepicker:
var nowTemp = new Date();
var now = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0);
var checkin = $('#dpd1').datepicker({
onRender: function (date) {
return date.valueOf() < now.valueOf() ? 'disabled' : '';
}
}).on('changeDate', function (ev) {
if (ev.date.valueOf() > checkout.date.valueOf()) {
var newDate = new Date(ev.date)
newDate.setDate(newDate.getDate() + 1);
checkout.setValue(newDate);
}
checkin.hide();
$('#dpd2')[0].focus();
}).data('datepicker');
var checkout = $('#dpd2').datepicker({
onRender: function (date) {
return date.valueOf() <= checkin.date.valueOf() ? 'disabled' : '';
}
}).on('changeDate', function (ev) {
checkout.hide();
}).data('datepicker');

I'm not 100% sure on what you're asking, but I think this might solve your problem (assuming the server knows how to handle blank values):
$(function () {
$("#SelectA").datepicker({
onSelect: handleSelectedDates
});
$("#SelectB").datepicker({
onSelect: handleSelectedDates
});
function handleSelectedDates(date) {
var A = $('#SelectA').val();
var B = $('#SelectB').val();
Method(A, B, "");
}
var ajaxReq;
function Method(A,B,C) {
if (ajaxReq)
ajaxReq.abort();
ajaxReq = $.ajax({
type: "POST",
url: "Services/MethodName.asmx/Method",
data: JSON.stringify({ A: A, B: B, C: "" }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
place the data into a table
}
});
}
});

Assuming you are using the jQuery datepicker (which this question has not yet been tagged), then you can simply use the onSelect method which will return the dates, which you can then check against and if statement and run your custom code.
Here is a jsfiddle. http://jsfiddle.net/xu8zZ/
$(function() {
$( "#datepicker" ).datepicker({
onSelect: function(dateText, inst) {
console.log(dateText);
console.log(inst);
}
});
});
Just look at your console when you select a date and you will see how it returns the date; at which time, you can write your condition.
Ref. http://api.jqueryui.com/datepicker/#option-onSelect

You can use one function to handle both events:
$(function () {
$("#SelectA,#SelectB").datepicker({
onSelect: function (date) {
var A = $('#SelectA').val();
if ($(this).attr("id") == "SelectB")
{
var B = $('#SelectB').val();
}
else
{
var B = "";
}
var C = "";
Method(A, B, C);
}
});
});

Related

Javascript/Jquery-UI make reusable function that checks if dateTo is after dateFrom

I have 2 datepickers. #datepicker0 and #datepicker1 and the following code to check if the date_from is after date_to:
$('#datepicker0').datepicker({
dateFormat: 'yy-mm-dd'
});
var valeDate = {
dateFormat: 'yy-mm-dd',
onSelect: function() {
if ($('#datepicker0').val() > $(this).val()) {
alert("Date problem");
$(this).val(null)
}
$(this).change();
}
}
$("#datepicker1").datepicker(valeDate).on("change", function() {
display("Change event");
I would like to remove the parameter #datepicker0 from the onSelect function in order to make the function reusable.
Could anyone show me how to make it?
function validateDate(datepicker, value) {
if (value > datepicker.val()) {
alert("Date problem")
datepicker.val(null)
}
datepicker.change()
}
var valeDate = {
dateFormat: 'yy-mm-dd',
onSelect: function() {
validateDate($(this), $('#datepicker0').val())
}
}
Next time, please address questions like this (everything works but code require modifications) to code review (https://codereview.stackexchange.com/)
finally i used this code:
function datepickerValidator(startDate,endDate) {
var datepickerFrom = startDate;
var datepickerTo = endDate;
// returns the millisecond obtained from the string 'dd-mm-yy'
function getTimeMillis(dateString) {
var splittedFrom = dateString.split("-");
var day = splittedFrom[0];
var month = splittedFrom[1];
var year = splittedFrom[2];
var dateTmp = new Date(year + "-" + month + "-" + day);
var timeMillis = dateTmp.getTime();
return timeMillis;
}
var validateDatePickerOption = {dateFormat: 'dd-mm-yy',
onSelect: function() {
from = getTimeMillis(datepickerFrom.val());
to = getTimeMillis($(datepickerTo).val());
if ( from > to ) {
alert("Date problem: value 'To' must be after 'From'");
$(this).val(null)
}
}
}
return validateDatePickerOption;
}
and for each datepicker:
var from = $("#From");
var to = $("#To");
var datepickerOption = datepickerValidator(from,to);
from.datepicker(datepickerOption);
to.datepicker(datepickerOption);

How to allow datepicker to pick future dates in JQuery?

I need a datepicker for our project and whilst looking online.. I found one. However, it disables to allow future dates. I tried looking into the code but I cannot fully understand it. I'm kind of new to JQuery.
This is the code (it's very long, sorry):
<script>
$.datepicker._defaults.isDateSelector = false;
$.datepicker._defaults.onAfterUpdate = null;
$.datepicker._defaults.base_update = $.datepicker._updateDatepicker;
$.datepicker._defaults.base_generate = $.datepicker._generateHTML;
function DateRange(options) {
if (!options.startField) throw "Missing Required Start Field!";
if (!options.endField) throw "Missing Required End Field!";
var isDateSelector = true;
var cur = -1,prv = -1, cnt = 0;
var df = options.dateFormat ? options.dateFormat:'mm/dd/yy';
var RangeType = {ID:'rangetype',BOTH:0,START:1,END:2};
var sData = {input:$(options.startField),div:$(document.createElement("DIV"))};
var eData = {input:null,div:null};
/*
* Overloading JQuery DatePicker to add functionality - This should use WidgetFactory!
*/
$.datepicker._updateDatepicker = function (inst) {
var base = this._get(inst, 'base_update');
base.call(this, inst);
if (isDateSelector) {
var onAfterUpdate = this._get(inst, 'onAfterUpdate');
if (onAfterUpdate) onAfterUpdate.apply((inst.input ? inst.input[0] : null), [(inst.input ? inst.input.val() : ''), inst]);
}
};
$.datepicker._generateHTML = function (inst) {
var base = this._get(inst, 'base_generate');
var thishtml = base.call(this, inst);
var ds = this._get(inst, 'isDateSelector');
if (isDateSelector) {
thishtml = $('<div />').append(thishtml);
thishtml = thishtml.children();
}
return thishtml;
};
function _hideSDataCalendar() {
sData.div.hide();
}
function _hideEDataCalendar() {
eData.div.hide();
}
function _handleOnSelect(dateText, inst, type) {
var localeDateText = $.datepicker.formatDate(df, new Date(inst.selectedYear, inst.selectedMonth, inst.selectedDay));
// 0 = sData, 1 = eData
switch(cnt) {
case 0:
sData.input.val(localeDateText);
eData.input.val('');
cnt=1;
break;
case 1:
if (sData.input.val()) {
var s = $.datepicker.parseDate(df,sData.input.val()).getTime();
var e = $.datepicker.parseDate(df,localeDateText).getTime();
if (e >= s) {
eData.input.val(localeDateText);
cnt=0;
}
}
}
}
function _handleBeforeShowDay(date, type) {
// Allow future dates?
var f = (options.allowFuture || date < new Date());
switch(type)
{
case RangeType.BOTH:
return [true, ((date.getTime() >= Math.min(prv, cur) && date.getTime() <= Math.max(prv, cur)) ?
'ui-daterange-selected' : '')];
case RangeType.END:
var s2 = null;
if (sData.input && sData.input.val()) {
try{
s2 = $.datepicker.parseDate(df,sData.input.val()).getTime();
}catch(e){}
}
var e2 = null;
if (eData.input && eData.input.val()) {
try {
e2 = $.datepicker.parseDate(df,eData.input.val()).getTime();
}catch(e){}
}
var drs = 'ui-daterange-selected';
var t = date.getTime();
if (s2 && !e2) {
return [(t >= s2 || cnt === 0) && f, (t===s2) ? drs:''];
}
if (s2 && e2) {
return [f, (t >= s2 && t <= e2) ? drs:''];
}
if (e2 && !s2) {
return [t < e2 && f,(t < e2) ? drs:''];
}
return [f,''];
}
}
function _attachCloseOnClickOutsideHandlers() {
$('html').click(function(e) {
var t = $(e.target);
if (sData.div.css('display') !== 'none') {
if (sData.input.is(t) || sData.div.has(t).length || /(ui-icon|ui-corner-all)/.test(e.target.className)) {
e.stopPropagation();
}else{
_hideSDataCalendar();
}
}
if (eData && eData.div.css('display') !== 'none') {
if (eData.input.is(t) || eData.div.has(t).length || /(ui-icon|ui-corner-all)/.test(e.target.className)) {
e.stopPropagation();
}else{
_hideEDataCalendar();
}
}
});
}
function _alignContainer(data, alignment) {
var dir = {right:'left',left:'right'};
var css = {
position: 'absolute',
top: data.input.position().top + data.input.outerHeight(true)
};
css[alignment ? dir[alignment]:'right'] = '0em';
data.div.css(css);
}
function _handleChangeMonthYear(year, month, inst) {
// What do we want to do here to sync?
}
function _focusStartDate(e) {
cnt = 0;
sData.div.datepicker('refresh');
_alignContainer(sData,options.opensTo);
sData.div.show();
_hideEDataCalendar();
}
function _focusEndDate(e) {
cnt = 1;
_alignContainer(eData,options.opensTo);
eData.div.datepicker('refresh');
eData.div.show();
sData.div.datepicker('refresh');
sData.div.hide();
}
// Build the start input element
sData.input.attr(RangeType.ID, options.endField ? RangeType.START : RangeType.BOTH);
sData.div.attr('id',sData.input.attr('id')+'_cDiv');
sData.div.addClass('ui-daterange-calendar');
sData.div.hide();
var pDiv = $(document.createElement("DIV"));
pDiv.addClass('ui-daterange-container');
// Move the dom around
sData.input.before(pDiv);
pDiv.append(sData.input.detach());
pDiv.append(sData.div);
sData.input.on('focus', _focusStartDate);
sData.input.keydown(function(e){if(e.keyCode==9){return false;}});
sData.input.keyup(function(e){
_handleKeyUp(e, options.endField ? RangeType.START : RangeType.BOTH);
});
_attachCloseOnClickOutsideHandlers();
var sDataOptions = {
showButtonPanel: true,
changeMonth: true,
changeYear: true,
isDateSelector: true,
beforeShow:function(){sData.input.datepicker('refresh');},
beforeShowDay: function(date){
return _handleBeforeShowDay(date, options.endField ? RangeType.END : RangeType.BOTH);
},
onChangeMonthYear: _handleChangeMonthYear,
onSelect: function(dateText, inst) {
return _handleOnSelect(dateText,inst,options.endField ? RangeType.END : RangeType.BOTH);
},
onAfterUpdate: function(){
$('<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" data-handler="hide" data-event="click">Done</button>')
.appendTo($('#'+sData.div.attr('id') + ' .ui-datepicker-buttonpane'))
.on('click', function () {
sData.div.hide();
});
}
};
sData.div.datepicker($.extend({}, options, sDataOptions));
// Attach the end input element
if (options.endField) {
eData.input = $(options.endField);
if (eData.input.length > 1 || !eData.input.is("input")) {
throw "Illegal element provided for end range input!";
}
if (!eData.input.attr('id')) {eData.input.attr('id','dp_'+new Date().getTime());}
eData.input.attr(RangeType.ID, RangeType.END);
eData.div = $(document.createElement("DIV"));
eData.div.addClass('ui-daterange-calendar');
eData.div.attr('id',eData.input.attr('id')+'_cDiv');
eData.div.hide();
pDiv = $(document.createElement("DIV"));
pDiv.addClass('ui-daterange-container');
// Move the dom around
eData.input.before(pDiv);
pDiv.append(eData.input.detach());
pDiv.append(eData.div);
eData.input.on('focus', _focusEndDate);
// Add Keyup handler
eData.input.keyup(function(e){
_handleKeyUp(e, RangeType.END);
});
var eDataOptions = {
showButtonPanel: true,
changeMonth: true,
changeYear: true,
isDateSelector: true,
beforeShow:function(){sData.input.datepicker('refresh');},
beforeShowDay: function(date){
return _handleBeforeShowDay(date, RangeType.END);
},
onSelect: function(dateText, inst) {
return _handleOnSelect(dateText,inst,RangeType.END);
},
onAfterUpdate: function(){
$('<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" data-handler="hide" data-event="click">Done</button>')
.appendTo($('#'+eData.div.attr('id') + ' .ui-datepicker-buttonpane'))
.on('click', function () {
eData.div.hide();
});
}
};
eData.div.datepicker($.extend({}, options, eDataOptions));
}
return {
// Returns an array of dates[start,end]
getDates: function getDates() {
var dates = [];
var sDate = sData.input.val();
if (sDate) {
try {
dates.push($.datepicker.parseDate(df,sDate));
}catch(e){}
}
var eDate = (eData.input) ? eData.input.val():null;
if (eDate) {
try {
dates.push($.datepicker.parseDate(df,eDate));
}catch(e){}
}
return dates;
},
// Returns the end date as a js date
getStartDate: function getStartDate() {
try {
return $.datepicker.parseDate(df,sData.input.val());
}catch(e){}
},
// Returns the start date as a js date
getEndDate: function getEndDate() {
try {
return $.datepicker.parseDate(df,eData.input.val());
}catch(e){}
}
};
}
var cfg = {startField: '#fromDate', endField: '#toDate',opensTo: 'Left', numberOfMonths: 3, defaultDate: -50};
var dr = new DateRange(cfg);
</script>
There is a comment along the code that says, "Allow Future Dates?" That's where I tried looking but I had no luck for hours now. Please help me.
This is how the date range picker looks like in my page:
Thank you so much for your help.
UPDATE: JSFIDDLE http://jsfiddle.net/dacrazycoder/4Fppd/
In cfg, add a property with key allowFuture with the value of true
http://jsfiddle.net/4Fppd/85/

Jquery: Unable to add Json object to Ajax request

Overview: I am making a web tool that displays the total number of movies sold by different studios on digital platform using charts(Highcharts). These charts are dynamic so the user has a list of filters he can use to change the result.
Filter 1 - Studios:
Using this filter the user can select different studios whose sales he would wish to see.
Filter 2 - Period:
This is the duration during of time for which he would want to see the sales.
It is this filter that is giveing me the problem.
Basically the selection of the period doesnot get sent with the AJAX request and hence has no effect on the chart. The default value for the period (Set using the momentjs library) also goes with the AJAX request. It is the change in the period that doesnt get added to the request.
There is no error message as such.
The Code:
$(document).ready(function(){
var btnStudiosDiv = $('#btnStudios');
var getStudios = function ()
// Get all studio's from buttons with .active class
var studios = $('button.active', btnStudiosDiv).map(function () {
return $(this).val();
}).get();
// If no studio's found, get studio's from any button.
if (!studios || studios.length <= 0) {
studios = $('button', btnStudiosDiv).map(function () {
return $(this).val();
}).get();
}
return studios;
};
var periodFrom = (moment().format('WW')-11)
var periodTo = moment().format('WW')
var output = {};
var show = function (studios) {
output['Studios'] = studios,
var per = {Period: {"From":["W" + periodFrom],"To":["W" + periodTo]}};
$.extend(output, per);
$('.list').html(JSON.stringify(output)); //Display Json Object on the Webpage
$.ajax({ //Ajax call to send the Json string to the server
type: "POST",
data: {"jsontring": JSON.stringify(output)},
url: "http://localhost:8080/salesvolume" ,
contentType: "application/json",
dataType: "json",
cache: false,
beforeSend: function() {
$('#container').html("<img class = 'ajload' src='loading.gif' />");
},
success: function(data){
alert( ) ;
$('#container').highcharts(data);
},
error: function() {
alert("Something is not OK :(")
},
});
};
var timer; //To create a time delay of 2 Secs for every selection
$(".btn").click(function () {
$(this).toggleClass('active');
// Fetch studios
var studios = getStudios();
// Remove previous timeOut if it hasn't executed yet.
if(timer)
clearTimeout(timer);
// Wait 2 sec
timer = setTimeout(function () {
// Fill list with the studios
show(studios);
},2000);
});
// Show the json on page load
show(getStudios());
//Period Selector (Template used from http://jqueryui.com/datepicker/)
$(function() {
var startDate;
var endDate;
var selectCurrentWeek = function() {
window.setTimeout(function () {
$('#weekpickerFrom').datepicker('widget').find('.ui-datepicker-current-day a').addClass('ui-state-active')
}, 1);
}
$('#weekpickerFrom').datepicker( {
showOn: "button",
buttonImage: "calendar2.gif",
buttonImageOnly: true,
buttonText: "Select date",
changeMonth: true,
changeYear: true,
showWeek: true,
showOtherMonths: false,
selectOtherMonths: false,
onSelect: function(dateText, inst) {
var date = $(this).datepicker('getDate');
startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay());
endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 6);
var dateFormat = inst.settings.dateFormat || $.datepicker._defaults.dateFormat;
$('#weekpickerFrom').val(date.getFullYear() + '/W'+$.datepicker.iso8601Week(new Date(dateText)));
output.Period.From = (date.getFullYear() + '/W'+$.datepicker.iso8601Week(new Date(dateText)));
periodFrom = output.Period.From //Add Period from to the Json String
if(timer)
clearTimeout(timer);
timer = window.setTimeout(function() {$('.list').html(JSON.stringify(output))},2000); //Display Json Object on the Webpage
selectCurrentWeek();
},
beforeShow: function() {
selectCurrentWeek();
},
beforeShowDay: function(date) {
var cssClass = '';
if(date >= startDate && date <= endDate)
cssClass = 'ui-datepicker-current-day';
return [true, cssClass];
},
onChangeMonthYear: function(year, month, inst) {
selectCurrentWeek();
}
}).datepicker('widget').addClass('ui-weekpickerFrom');
$('.ui-weekpickerFrom .ui-datepicker-calendar tr').on('mousemove', function() { $(this).find('td a').addClass('ui-state-hover'); });
$('.ui-weekpickerFrom .ui-datepicker-calendar tr').on('mouseleave', function() { $(this).find('td a').removeClass('ui-state-hover'); });
});
$(function() {
var startDate;
var endDate;
var selectCurrentWeek = function() {
window.setTimeout(function () {
$('#weekpickerTo').datepicker('widget').find('.ui-datepicker-current-day a').addClass('ui-state-active')
}, 1);
}
$('#weekpickerTo').datepicker( {
showOn: "button",
buttonImage: "calendar2.gif",
buttonImageOnly: true,
buttonText: "Select date",
changeMonth: true,
changeYear: true,
showWeek: true,
showOtherMonths: false,
selectOtherMonths: false,
onSelect: function(dateText, inst) {
var date = $(this).datepicker('getDate');
startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay());
endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 6);
var dateFormat = inst.settings.dateFormat || $.datepicker._defaults.dateFormat;
$('#weekpickerTo').val(date.getFullYear() + '/W'+$.datepicker.iso8601Week(new Date(dateText)));
output.Period.To = (date.getFullYear() + '/W'+$.datepicker.iso8601Week(new Date(dateText)));
periodTo = output.Period.From //Add Period to to the Json String
if(timer)
clearTimeout(timer);
timer = window.setTimeout(function() {$('.list').html(JSON.stringify(output))},2000); //Display Json Object on the Webpage
selectCurrentWeek();
},
beforeShow: function() {
selectCurrentWeek();
},
beforeShowDay: function(date) {
var cssClass = '';
if(date >= startDate && date <= endDate)
cssClass = 'ui-datepicker-current-day';
return [true, cssClass];
},
onChangeMonthYear: function(year, month, inst) {
selectCurrentWeek();
}
}).datepicker('widget').addClass('ui-weekpickerTo');
$('.ui-weekpickerTo .ui-datepicker-calendar tr').on('mousemove', function() { $(this).find('td a').addClass('ui-state-hover'); });
$('.ui-weekpickerTo .ui-datepicker-calendar tr').on('mouseleave', function() { $(this).find('td a').removeClass('ui-state-hover'); });
});
});
It would be really helpful if someone could point out where I am going wrong.
Note: There are multiple other filter added on the tool, however for simplicity 1 have just mentioned the two important ones.
I think data should be like this
$.ajax({
type: "POST",
**data: "{\"jsontring\":" + JSON.stringify(output) + "}",**
url: "http://localhost:8080/salesvolume" ,
contentType: "application/json",
dataType: "json",
cache: false,
beforeSend: function() {
$('#container').html("<img class = 'ajload' src='loading.gif' />");
},
success: function(data){
alert( ) ;
$('#container').highcharts(data);
},
error: function() {
alert("Something is not OK :(")
},
});
In your Ajax request

Use jQuery UI datepicker with async AJAX requests

I am trying to enable specific days in a jquery-ui datepicker. So far i have set my sql scripts and json files and everything is working fine except the response time, because i've set async to false. My jquery code is.
var today = new Date();
$("#pickDate").datepicker({
minDate: today,
maxDate: today.getMonth() + 1,
dateFormat: 'dd-mm-yy',
beforeShowDay: lessonDates,
onSelect: function(dateText) {
var selectedDate = $(this).datepicker('getDate').getDay() - 1;
$("#modal").show();
$.get("http://localhost/getTime.php", {
lessonDay: selectedDate,
lessonId: $("#lesson").val()
}, function(data) {
$("#attend-time").html("");
for (var i = 0; i < data.length; i++) {
$("#attend-time").append("<option>" + data[i].lessonTime + "</option>");
$("#modal").hide();
}
}, 'json');
}
});
function lessonDates(date) {
var day = date.getDay();
var dayValues = [];
$.ajax({
type: "GET",
url: "http://localhost/getLessonDay.php",
data: {
lessonId: $("#lesson").val()
},
dataType: "json",
async: false,
success: function(data) {
for (var i = 0; i < data.length; i++) {
dayValues.push(parseInt(data[i].lessonDay));
}
}
});
if ($.inArray(day, dayValues) !== -1) {
return [true];
} else {
return [false];
}
}
Can anyone help me out? I repeat the above code is working fine but with not good response time due to async=false.
Thanks!
You are doing it all wrong. In your example, a synchronous AJAX request is fired for every day in the month. You need to re-factor your code like this (rough outline):
// global variable, accessible inside both callbacks
var dayValues = [];
$("#pickDate").datepicker({
beforeShowDay: function(date) {
// check array and return false/true
return [$.inArray(day, dayValues) >= 0 ? true : false, ""];
}
});
// perhaps call the following block whenever #lesson changes
$.ajax({
type: "GET",
url: "http://localhost/getLessonDay.php",
async: true,
success: function(data) {
// first populate the array
for (var i = 0; i < data.length; i++) {
dayValues.push(parseInt(data[i].lessonDay));
}
// tell the datepicker to draw itself again
// the beforeShowDay function is called during the processs
// where it will fetch dates from the updated array
$("#pickDate").datepicker("refresh");
}
});
See similar example here.
$.when(getdates()).done(function() {
//this code is executed when all ajax calls are done => the getdates() for example
$('#res_date').datepicker({
startDate: '-0m',
format: 'dd/mm/yyyy',
todayHighlight:'TRUE',
autoclose: true,
datesDisabled: unavailableDates,
});
});
function getdates() {
return $.ajax({
type:'GET',
url:'/available_dates',
success: function(response) {
for (let i = 0; i < response.data.length; i++) {
unavailableDates.push(response.data[i]);
}
console.log(unavailableDates);
return unavailableDates;
},
});
}

Accept pre-populated form field input

I just set up my date-picker to auto populate it's input field with today's date.
Normally, a user would have to select their own date and submit their selection via the enter key or, I think in my case, any key would do it.
Is there anyway to automatically do this? Since the field is pre-populated, I want the results for today's date to appear automatically on page load, without the user needing to accept the date(today) that has been pre-populated into the field.
Here's my code if it's helpful:
<script>
function displayResult() {
var k;
if (window.event) // IE8 and earlier
{
k = event.keyCode;
} else if (event.which) // IE9/Firefox/Chrome/Opera/Safari
{
k = event.which;
}
if (k == 13) //13 = 'Enter' key
{
var dt = $("#datepicker").val();
//alert(dt);
if (dt != '') {
$.ajax({
type: "POST",
url: "search_date.php",
data: "dt=" + dt,
success: function (option) {
$("#results").html(option).listview("refresh");
}
});
} else {
$("#results").html("");
}
return false;
}
}
</script>
<script type="text/javascript">
$(function () {
$("#datepicker").datepicker();
$("#datepicker").datepicker("setDate", new Date());
$('#datepicker').datepicker({
inline: true,
showOn: "button",
buttonImage: "images/calendar.gif",
showAnim: "slideDown",
changeMonth: true,
showOtherMonths: true,
selectOtherMonths: true,
onSelect: function (dateText, inst) {
//alert($('#datepicker').datepicker( "getDate" ))
//alert("dateText: " + dateText + ", inst: " + inst);
var dt = dateText;
if (dt != '') {
$.ajax({
type: "POST",
url: "search_date.php",
data: "dt=" + dt,
success: function (option) {
$("#results").html(option).listview("refresh");
}
});
} else {
$("#results").html("");
}
return false;
}
});
$('body').ready(function(){
var dt = $("#datepicker").val();
//alert(dt);
if(dt != '')
{
$.ajax
({
type: "POST",
url: "search_date.php",
data: "dt="+ dt,
success: function(option)
{
$("#results").html(option).listview("refresh");
}
});
}
else
{
$("#results").html("");
}
return false;
});
</script>
$('body').ready(function(){
var dt = $("#datepicker").val();
//alert(dt);
if(dt != '')
{
$.ajax
({
type: "POST",
url: "search_date.php",
data: "dt="+ dt,
success: function(option)
{
$("#results").html(option).listview("refresh");
}
});
}
else
{
$("#results").html("");
}
return false;
});

Categories