0

I'm working on a web site but now I have a issue were I can change the first input but not the second one whiteout triggering the on blur.
I expect when I click outside of the inputs it will trigger the Ajax and but hen I click on the input I can change it.

my code:

let shiftId = 0;
let userId = 0;
let date = 0;
$(document).ready(function () {
  $(document).on("dblclick", ".shift", function () {
    let cell = $(this);
    shiftId = cell.find(".shift-value").attr("id");
    userId = cell.find(".shift-value").attr("user-id");
    date = cell.find(".shift-value").attr("date");
    console.log(userId);
    let currentValue = cell.text().trim();
    let inputs =
      '<input type="time" class="start" value="' +
      currentValue.split("-")[0] +
      '"> - <input type="time" class="end" value="' +
      currentValue.split("-")[1] +
      '">';
    cell.html(
      "<div class='shift-value' date=" +
        date +
        " user-id=" +
        userId +
        "  id=" +
        shiftId +
        ">" +
        inputs +
        "</div>"
    );
    cell.find(".start").focus();
  });

  $(document).on("blur", ".shift input", function () {
    let cell = $(this).parent();
    let start = cell.find(".start").val();
    let end = cell.find(".end").val();
    console.log(shiftId);
    let currentValue = start + "-" + end;

    if (currentValue !== "00:00-00:00") {
      // Create new shift if it was previously empty
      cell.html(currentValue);
      $.ajax({
        url: "rooster/create_shift.php",
        method: "POST",
        data: {
          start_time: start,
          date: date,
          end_time: end,
          user_id: userId,
          shiftId: shiftId,
        },
        success: function (response) {
          console.log(response);
        },
        error: function (xhr, status, error) {
          console.error(xhr.responseText);
        },
      });
      return;
    } else if (currentValue == "00:00-00:00") {
      // Delete shift if it was previously not empty
      cell.html(currentValue);
      $.ajax({
        url: "rooster/delete_shift.php",
        method: "POST",
        data: {
          shift_id: shiftId,
        },
        success: function (response) {
          console.log(response);
        },
        error: function (xhr, status, error) {
          console.error(xhr.responseText);
        },
      });
    } else {
      // Reset cell to previous value
      cell.html(currentValue);
    }
  });
});
eglease
  • 2,445
  • 11
  • 18
  • 28
  • The `blur` event happens whenever you leave an input. So when you click on one input, you have to leave the other one, which triggers its `blur` event. – Barmar Apr 10 '23 at 18:02
  • If you want the AJAX to happen when you click anywhere outside any of the inputs, don't use `blur`. Use a `click` on `:not('.shift input')` – Barmar Apr 10 '23 at 18:03

0 Answers0