Home > OS >  Pass data into datepicker from input-field using jQuery
Pass data into datepicker from input-field using jQuery

Time:11-17

I'm trying to create a form where the user can choose two dates.

To do this, I'm using datepicker.

JavaScript to display the input field:

        let form = document.getElementById("dateform");

        let output = "<div>";
        output  =
          "<input type='text' id='date"   i   "' onFocus='pickdate("  i  ")'><br/>";
        output  = "</div>";

        form.innerHTML = output;

The "i" is used because I have several things the user can book dates for in a table. So in order to not book the same thing over and over again I've created a loop to give each product a unique id.

      function pickdate(i) {
        $(document).ready(function () {
          date = $("#date"   i).datepicker();
        });
      }

Now, this code works. The problem I'm having is that I have to click on the datepicker twice in order for it to show.

The only way I've managed to get the datepicker to pop up on the first click is by using this:

      $(document).on("focus", "#date1", function () {
        $(this).datepicker();
      });

By using this I don't have to call the function in the html either.

I however, here give the "i" value manually in "id="#date1". I need it to be dynamic and come from the product the user clicks on. With JavaScript I can just send the variable like I've done above. But how do I send the "i" value into the function with jQuery?

Thank you.

EDIT:

I tried my best to recreate the problem:

https://codepen.io/leoss/pen/gOKGRML

CodePudding user response:

If you add the same css class to each <input/> and remove the onFocus like so:

let dateOutput  = "<div class='booking-dates'>";
  dateOutput  =
    "<input type='text' class='my-date-picker' id='date"   i  "' />;

You can initialize all of the date pickers at once with something like:

$(document).ready(function () {
  $('.my-date-picker').datepicker({
    onSelect: function (date) {

    }
  });
});

You might not even need the id attribute at all.

Here is a codepen that combines your example with my example above and shows both how to initialize an arbitrary number of datepickers at once and how to find the i of the datepicker where a date was picked.

  • Related