onClick requires 2 clicks

Viewed 110

I am using this JQuery Time Picker.

        <fieldset class="input-field">
          <svg>
            <use xlink:href="images/icons.svg#clock"></use>
          </svg>

          <input
            type="text"
            name="empCheckinTime"
            id="empCheckinTime"
            onclick="pickTime('#empCheckinTime')"  // This event works only on the second click
            required
          />

          <label for="empCheckinTime">Check-in Time</label>
        </fieldset>

        <script>
          function pickTime(element) {
            $(element).timepicker({ timeFormat: "H:i:s" })
          }
       </script>

I have faced this issue before. Back then, I used setTimeout to delay the function call by 50ms. This time it didn't work.

2 Answers

You could just do this instead:

$(document).ready(function() {
   $("#empCheckinTime").timepicker({ timeFormat: "H:i:s" });
});

You can do this by having a more dynamic approach by using a class selection on your inputs - If the use an id for timePicker to initialize then you will be repeating the same code multiple times.

You will have check out time input as well. so yeah using a class will work on all the inputs.

Also, avoid inline events wherever possible - not rec-emended to use inline events like onClick or etc. In you case you do not even need an inline onclick function.

$(document).ready(function() {
   $(".timePicker").timepicker({ timeFormat: "H:i:s" });
});

Live Working Demo:

$(document).ready(function() {
  $(".timePicker").timepicker({
    timeFormat: "H:i:s"
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/timepicker@1.13.14/jquery.timepicker.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/timepicker@1.13.14/jquery.timepicker.css">

<fieldset class="input-field">
  <svg>
    <use xlink:href="images/icons.svg#clock"></use>
  </svg>

  <input type="text" class="timePicker" name="empCheckinTime" id="empCheckinTime" />
  <label for="empCheckinTime">Check-in Time</label>
  <input type="text" class="timePicker" name="empCheckoutTime" id="empCheckoutTime" />
  <label for="empCheckoutTime">Check-Out Time</label>
</fieldset>

Related