What could be causing my concentration to be so off?

When I load the data.json file after focusing, my datepicker does not show up. This puzzles me because it appears on the second focus attempt. Where could I be going wrong?

function flattenFieldsArray(arr) {
      return arr.map(function(item) {
        return item.field
      })
    }
    $(function() {
     var focused = false;
       $(document.body).one("focus", '#checkin,#checkout', function() {
          if (!focused) {
            
      
             $.getJSON('data.json', function(data) {
      


        // The rest of the code remains unchanged Unfortunately, I couldn't include my JSON data in this snippet, so please refer to the Plunker demo for a working example.

.form{
  width:960px;
  margin:120px auto;
}
.form input{
  width:250px;
  padding:10px;
}
.ui-highlight .ui-state-default{background: red !important;border-color: red !important;color: white !important; cursor:no-drop;}
.ui-bos .ui-state-default{background: green !important;border-color: green !important;color: white !important;}
.ui-ss .ui-state-default{background: yellow !important;border-color: yellow !important;color: gray !important; cursor:help;}
.ui-ss-donus .ui-state-default{background: yellow !important;border-color: yellow !important;color: gray !important; cursor:help;}
.ui-highlight-donus .ui-state-default{background: red !important;border-color: red !important;color: white !important; }
.ui-testtarih .ui-state-default{
  background:black !important;
  color:#FFF !important;
}
<link data-require="jqueryui" data-semver="1.10.0" rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.10.0/css/smoothness/jquery-ui-1.10.0.custom.min.css" />

   <div class="form">
    <input type="text" id="checkin" />
    <input type="text" id="checkout" />
    <input type="submit" value="Search" />
  </div>
 
 <script data-require="jquery" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script data-require="jqueryui" data-semver="1.10.0" src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.10.0/jquery-ui.js"></script>

footnote: You can also check out the Plunker demo here.

Answer №1

$.getJSON has a handy done() function that allows you to execute your code after the data has been loaded. You can manually activate the datepicker within this function.

To see it in action, check out this modified version

Answer №2

One reason for this behavior is that, initially, the datepickers are applied to the elements but not triggered. It's important to distinguish between binding an event and triggering it. Upon first focus, the datepicker is applied but not triggered because it hasn't been bound to the element yet. However, on subsequent focuses, the datepicker will be triggered and open since it is already bound.

To solve this issue, you can try adding

$("#checkin").datepicker('show');
and
$("#checkout").datepicker('show');
after the initialization of the datepickers using $("#checkin").datepicker({}) and $("#checkout").datepicker({}), respectively.

Answer №3

Prior to triggering the initial focus event on your datepickers, ensure that you load your data.

Check out an example here:

plunkr

$( document ).ready(function() {
    var data;
    $.getJSON('data.json', function (d) {
        data = d;
        console.log('data', d);
        setupDatepickers();
    });

    function setupDatepickers() {
        // use ajax data mapped to same structure as original variables
                 var firstDate = flattenFieldsArray(data.firstDate);
                 var lastDate = flattenFieldsArray(data.lastDate);
                 var availabledays = flattenFieldsArray(data.availabledays);
                 var booked = flattenFieldsArray(data.booked);;
                 var ssdays = [];

                 // no modifications were made below

                 var dateFormat = "mm/dd/yy",
                     from       = $("#checkin")
                         .datepicker({
                             beforeShowDay : function (date) {
                                 var y = date
                                     .getFullYear()
                                     .toString(); // get full year
                                 var m = (date.getMonth() + 1).toString(); // get month.
                                 var d = date
                                     .getDate()
                                     .toString(); // get Day
                                 if (m.length == 1) {
                                     m = '0' + m;
                                 } // append zero(0) if single digit
                                 if (d.length == 1) {
                                     d = '0' + d;
                                 } // append zero(0) if single digit
                                 var currDate = y + '-' + m + '-' + d;
                                 if (jQuery.inArray(currDate, availabledays) >= 0) {
                                     return [false, "ui-highlight"];
                                 }

                                 if (jQuery.inArray(currDate, booked) >= 0) {
                                     return [true, "ui-bos"];
                                 } else {
                                     return [true];
                                 }

                             },
                             changeMonth   : true,
                             firstDay      : 1,
                             isTo1         : true,
                             maxDate       : new Date(lastDate),
                             minDate       : new Date(firstDate),
                             numberOfMonths: 2,
                             onSelect      : function (selectedDate) {
                                 var yenitarih = new Date();

                                 var date = $(this).datepicker('getDate');
                                 date.setTime(date.getTime() + (1000 * 60 * 60 * 24))

                                 $("#checkout").datepicker("option", "minDate", date);
                             }
                         })
                         .on("change", function () {
                             to.datepicker("option", "minDate", getDate(this));
                         }),
                     to         = $("#checkout")
                         .datepicker({
                             beforeShowDay : function (date) {
                                 var y = date
                                     .getFullYear()
                                     .toString(); // get full year
                                 var m = (date.getMonth() + 1).toString(); // get month.
                                 var d = date
                                     .getDate()
                                     .toString(); // get Day
                                 if (m.length == 1) {
                                     m = '0' + m;
                                 } // append zero(0) if single digit
                                 if (d.length == 1) {
                                     d = '0' + d;
                                 } // append zero(0) if single digit
                                 var currDate = y + '-' + m + '-' + d;

                                 if (jQuery.inArray(currDate, booked) >= 0) {
                                     return [true, "ui-highlight-donus"];
                                 }

                                 if (jQuery.inArray(currDate, availabledays) >= 0) {
                                     return [true, "ui-bos"];
                                 }

                                 if (jQuery.inArray(currDate, ssdays) >= 0) {
                                     return [true, "ui-ss-donus"];
                                 } else {
                                     return [true];
                                 }
                             },
                             changeMonth   : true,
                             changeYear    : true,
                             firstDay      : 1,
                             maxDate       : new Date(lastDate),
                             minDate       : new Date(firstDate),
                             numberOfMonths: 2,
                             onSelect      : function (selectedDate) {
                                 $("#checkin").datepicker("option", "maxDate", selectedDate);
                             }
                         })
                         .on("change", function () {
                             from.datepicker("option", "maxDate", getDate(this));
                         });

    }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The hamburger menu is not functioning properly online, but it works perfectly in xampp/localhost

I'm currently facing a challenge with my responsive menu. It works perfectly on my offline server in mobile format, but as soon as I upload it to the real server, it stops working. I've been grappling with this problem for hours. Here's the ...

Extracting Key from JSON Response Utilizing CakePHP for JQGrid Column Summarization

I'm sending JSON-encoded results from my controller to my view and displaying the data in jqGrid. The data is being displayed without any issues. However, I have added two integers to the response that I am returning and I want to display them in the ...

Unable to transfer object from Angular service to controller

I am currently utilizing a service to make a $http.get request for my object and then transfer it to my controller. Although the custom service (getService) successfully retrieves the data object and saves it in the responseObj.Announcement variable when ...

Tips for avoiding anti-aliasing of bitmap font on Internet Explorer and Firefox

I am currently experiencing issues with font smoothing when using a basic bitmap font for icons. While the font appears crisp in Chrome, it appears blurry in IE and FF. Do you have any recommendations on how to resolve this problem? You can view a screen ...

Chrome does not support gradient, while Firefox does

When I attempt to utilize the webkit gradient tag specifically for Chrome, it fails to function altogether. On the other hand, when tested on Firefox using background:-moz-linear-gradient(#000, #888);, it operates smoothly. Despite this, applying backgrou ...

The error message indicates that xxx does not function as a constructor

var Fishbowl = require('node-fishbowl'); var fb = new Fishbowl.Fishbowl({ host: 'X.X.X.X', IADescription: 'Reporting Dashboard', IAID: 2286, IANAME: 'node-dashboard', password: 'X', ...

Can the swipe navigation feature be disabled on mobile browsers?

Currently, I am in the process of creating a VueJS form that consists of multiple steps and includes a back button for navigating to the previous step. The steps are all managed within a parent component, which means that the URL and router history remain ...

The Mongoose function findbyIdAndRemove is currently not working properly when triggered on the client-side

I have a specific route in my app that uses the mongoose method findByIdAndRemove. Strangely, when I test this route using postman, it successfully deletes documents from my database. However, when I try to call this method from my client-side JavaScript f ...

Stagnant updates in component's styling

I have a list box style stored in the component's data. It is bound to a listbox element. One of the styles within it is position: absolute. My goal is to position the box directly below the input element. To achieve this, I am trying to dynamically m ...

Create a small circle in the bottom left corner with a constrained size

I'm trying to create a circle at the top of the screen on mobile, similar to the image below. The circle should take up a percentage of space, with the rest of the content appearing against a blue background as shown in the image. However, I'm h ...

The fetch API is being restricted, however, AJAX and XHR are still operational

I made an API call to a URL shortener and encountered different responses using Fetch, JQuery, and XHR. Why is Fetch returning a 400 error while the other methods work smoothly? Even after trying mode: 'no-cors' and "crossDomain": true in the re ...

Issue with Bootstrap datetime picker not adhering to step size

Currently, I am using a datetimepicker that has a stepping value of 45. However, I have noticed that when I increase the minutes, the hour field also increases by 1 hour. $("#startDate").datetimepicker({ format:'YYYY/MM/DD HH:mm' , locale: g_sta ...

JavaScript does not support the enumeration of programs

I'm currently working on a program that takes user input (library, authorName) and displays the titles of books written by the author. Here is an example library structure: let library = [ { author: 'Bill Gates', title: 'The Road Ah ...

Node.js in action with XmlHttpRequest

I'm having trouble making an XMLHttpRequest call from my client-side JavaScript to my Node server. It seems like nothing is happening and I'm a bit new to this concept. Here's the JavaScript function I've written: function sendTokenToS ...

Undefined value for req.query in Node.js Express

When working with Node.js and Express 4.7.2, I'm running the code below: express.get('/test1',function(req, res) { var ttt = false; if (req.query.username === undefined) ttt = true; res.json({query: ttt}); }); After calling the URL: ...

What is the best way to handle a struct coming from a cfc in jQuery?

Need help with my cfc <cffunction name="addEditPerson" access="remote" returntype="struct"> a lot of cfarguments <cfscript> var returnThis = structNew(); var error = ''; structInsert(returnThis,&a ...

Hide the drawer when a user clicks on a currently selected tab

Just starting to explore Material-UI and React here, so please bear with me if I'm making any rookie mistakes. :) I've set up a Drawer component containing a Tabs element with multiple Tab components inside. It's nothing too fancy yet - mos ...

Guide to retrieving JSON key and value using AJAX

Is there a way for me to retrieve my json object using the table header as the key and displaying the corresponding values in an HTML table? history:{1/22/20: 2, 1/23/20: 3, 1/24/20: 5, 2/1/20: 19, 2/10/20: 32, 2/11/20: 33, 2/12/20: 33, 2/2/20: 19, 2/20/2 ...

generate distinct identifier for django feedback form

I'm currently working on creating a wall feature similar to what can be found on Facebook, including comments and more. For this project, I am utilizing Django's comments framework and jQuery for posting and getting data successfully. My goal is ...

Transfer dropzone files exclusively upon pressing a button

Greetings to all! I am a newcomer here, and I am also new to jquery. I came across an article that explains how to upload multiple files at once on a website using Dropzone.js in ASP.NET Webforms. You can find the article here. Upon implementing the code ...