Не удается удалить в автоматическом формате с помощью JavaScript - PullRequest
0 голосов
/ 03 октября 2019

1.

Вот оригинальная дата автоматического форматирования , сделанная кем-то другим,

, поэтому дата похожа на 12 / 12 / 2019, мы используем space / space для разделениячисло.

2.

Я хочу использовать формат, подобный 12/12/2019, со следующим, но, похоже, я не могу удалить.

Этокодовое перо у меня есть

var outV = v.length == 2 && i < 2 ? v + "/" : v;

Это новый код, который у меня есть


<html>
  <head>
    <style>
      html {
        /* box */
        box-sizing: border-box;
        /* family */
        font-family: "PT Sans", sans-serif;
        /* smooth */
        -webkit-font-smoothing: antialiased;
      }

      /* all box */
      *,
      *:before,
      *:after {
        box-sizing: inherit;
      }

      /* body bg */
      body {
        background-color: #f3f3f3;
      }

      /* form */
      form {
        width: 100%;
        max-width: 400px;
        margin: 60px auto;
      }

      /* form input */
      form input {
        /* big box */
        font-size: 30px;
        padding: 0 20px;
        border: 2px solid #ccc;
        width: 100%;
        color: #666;
        line-height: 3;
        border-radius: 7px;
        font-family: "PT Sans", sans-serif;
        font-weight: bold;
      }

      form input:focus {
        outline: 0;
      }
      form input.error {
        border-color: #ff0000;
      }
      form label.error {
        background-color: #ff0000;
        color: #fff;
        padding: 6px;
        font-size: 11px;
      }

      label {
        color: #999;
        display: block;
        margin-bottom: 10px;
        text-transform: uppercase;
        font-size: 18px;
        font-weight: bold;
        letter-spacing: 0.05em;
      }

      /* use small */
      form small {
        color: #888;
        font-size: 1em;
        margin-top: 10px;
        display: block;
        align-self: ;
      }
    </style>
  </head>

  <body>
    <!-- https://codepen.io/tutsplus/pen/KMWqRr -->
    <form id="form" method="post" action="">
      <label for="amount">Date</label>
      <input type="text" id="date" />
      <small>Enter date as Day / Month / Year</small>
    </form>
  </body>

  <script>
    // input date by id
    var date = document.getElementById("date");

    // check val, str?, max?
    function checkValue(str, max) {
      // 1. 02, we don't check, because 0->12 (month) or 0->31
      // 2. 00, we check
      if (str.charAt(0) !== "0" || str == "00") {
        //test
        console.log("&& in");

        // str to num
        var num = parseInt(str);

        // 1. not a number (below code, already filter out \D)
        // 2. # <= 0, e.g. -1
        // 3. 32 > 21 in month
        // default to 1
        if (isNaN(num) || num <= 0 || num > max) num = 1;

        // 1. month: 3 > 12's 1st char ==> 03
        // 2. month: 1 <= 12's 1st char ===> 1.toStr, later more #
        // 3. day: 2 <= 31's 1st chr ===> 2.toStr, later more #
        str =
          num > parseInt(max.toString().charAt(0)) && num.toString().length == 1
            ? "0" + num // self, no more #
            : num.toString(); // can be more num
      }
      return str;
    }

    // user typing
    date.addEventListener("input", function(e) {
      //test
      console.log("=== listen input ====", this.value);

      // date input type is text
      this.type = "text";
      // date input value to var
      var input = this.value;

      // del is \D, non-digit
      // e.g. 02/ -> del 2 -> actual del 2/ -> 0 (left)
      //if (/\D\/$/.test(input)) {
      if (/\/$/.test(input)) {
        //test
        console.log("--digi slash--", input);

        // substr, last exclude, len-3
        input = input.substr(0, input.length - 3);

        //test
        console.log("--digi slash after--", input);
      }

      // remove non-digi
      var values = input.split("/").map(function(v) {
        // \D is not digit, so replace not digit to ""
        var replacedV = v.replace(/\D/g, "");
        return replacedV;
      });

      // e.g.
      // month, day
      // values == ["01", "12"]

      // check date, may not have
      if (values[0]) values[0] = checkValue(values[0], 31);

      // check month, may not have
      if (values[1]) values[1] = checkValue(values[1], 12);

      var output = values.map(function(v, i) {
        // test
        console.log("*** add slash", i);

        //var outV = v.length == 2 && i < 2 ? v + " / " : v;
        var outV = v.length == 2 && i < 2 ? v + "/" : v;

        return outV;
      });

      // join everything,
      console.log("output", output);
      console.log("substr", output.join("").substr(0, 14));

      // e.g. 01/01/1992 ==> 9 chars
      // 01 / 01 / 1992 ==> 13 chars
      this.value = output.join("").substr(0, 14);

      console.log(">>> this.value", this.value);
    });
  </script>
</html>

1 Ответ

0 голосов
/ 03 октября 2019

В оригинальной ручке между слешами есть пробел. Поэтому, когда пользователь удаляет пробел, мы можем проверить, является ли последний символ символом «/», и удаляет символ перед этим.

В вашем случае нет места. В любой момент ваш слушатель изменений вызывается с последним символом в качестве числа.

Так что вы не можете использовать этот подход. В этом случае я бы посоветовал отследить предыдущее значение и использовать его для удаления символа перед "/".

Пример if prevValue = "12/12/", и пользователь нажимает кнопку удаления, слушатель ввода вызывается со значением 12/12. На данный момент вы не можете решить, будет ли это удалить или вставить.

Вы можете использовать предыдущий ввод для решения этого if (prevInput.length > input.length && /\d\/$/.test(prevInput)) {

Если вам нужен кодовый блок, добавлен ниже.

https://codepen.io/nithinthampi/pen/XWWrJRz

Окончательное решение ниже,Надеюсь, это поможет!

<html>
  <head>
    <style>
      html {
        /* box */
        box-sizing: border-box;
        /* family */
        font-family: "PT Sans", sans-serif;
        /* smooth */
        -webkit-font-smoothing: antialiased;
      }

      /* all box */
      *,
      *:before,
      *:after {
        box-sizing: inherit;
      }

      /* body bg */
      body {
        background-color: #f3f3f3;
      }

      /* form */
      form {
        width: 100%;
        max-width: 400px;
        margin: 60px auto;
      }

      /* form input */
      form input {
        /* big box */
        font-size: 30px;
        padding: 0 20px;
        border: 2px solid #ccc;
        width: 100%;
        color: #666;
        line-height: 3;
        border-radius: 7px;
        font-family: "PT Sans", sans-serif;
        font-weight: bold;
      }

      form input:focus {
        outline: 0;
      }
      form input.error {
        border-color: #ff0000;
      }
      form label.error {
        background-color: #ff0000;
        color: #fff;
        padding: 6px;
        font-size: 11px;
      }

      label {
        color: #999;
        display: block;
        margin-bottom: 10px;
        text-transform: uppercase;
        font-size: 18px;
        font-weight: bold;
        letter-spacing: 0.05em;
      }

      /* use small */
      form small {
        color: #888;
        font-size: 1em;
        margin-top: 10px;
        display: block;
      }
    </style>
  </head>

  <body>
    <!-- https://codepen.io/tutsplus/pen/KMWqRr -->
    <form id="form" method="post" action="">
      <label for="amount">Date</label>
      <input type="text" id="date" />
      <small>Enter date as Day / Month / Year</small>
    </form>
  </body>

  <script>
    // input date by id
    var date = document.getElementById("date");

    // check val, str?, max?
    function checkValueWrapper() {
      var prevValue = "";
      return function updatePrevValue(newValue) {
        prevValue = newValue;
      };
    }

    function checkValue(str, max) {
      // 1. 02, we don't check, because 0->12 (month) or 0->31
      // 2. 00, we check
      if (str.charAt(0) !== "0" || str == "00") {
        //test
        console.log("&& in");

        // str to num
        var num = parseInt(str);

        // 1. not a number (below code, already filter out \D)
        // 2. # <= 0, e.g. -1
        // 3. 32 > 21 in month
        // default to 1
        if (isNaN(num) || num <= 0 || num > max) num = 1;

        // 1. month: 3 > 12's 1st char ==> 03
        // 2. month: 1 <= 12's 1st char ===> 1.toStr, later more #
        // 3. day: 2 <= 31's 1st chr ===> 2.toStr, later more #
        str =
          num > parseInt(max.toString().charAt(0)) && num.toString().length == 1
            ? "0" + num // self, no more #
            : num.toString(); // can be more num
      }
      return str;
    }

    function wrapEventListener() {
      var prevInput = "";
      return function(e) {
        //test
        console.log("=== listen input ====", this.value);

        // date input type is text
        this.type = "text";
        // date input value to var
        var input = this.value;

        // del is \D, non-digit
        // e.g. 02/ -> del 2 -> actual del 2/ -> 0 (left)
        //if (/\D\/$/.test(input)) {
        //if prevInput length id greate e
        if (prevInput.length > input.length && /\d\/$/.test(prevInput)) {
          //test
          console.log("--digi slash--", input);

          // substr, last exclude, len-3
          input = input.substr(0, input.length - 1);

          //test
          console.log("--digi slash after--", input);
        }

        // remove non-digit
        var values = input.split("/").map(function(v) {
          // \D is not digit, so replace not digit to ""
          var replacedV = v.replace(/\D/g, "");
          return replacedV;
        });

        // e.g.
        // month, day
        // values == ["01", "12"]

        // check date, may not have
        if (values[0]) values[0] = checkValue(values[0], 31);

        // check month, may not have
        if (values[1]) values[1] = checkValue(values[1], 12);

        var output = values.map(function(v, i) {
          // test
          console.log("*** add slash", i);

          //var outV = v.length == 2 && i < 2 ? v + " / " : v;
          var outV = v.length == 2 && i < 2 ? v + "/" : v;

          return outV;
        });

        // join everything,
        console.log("output", output);
        console.log("substr", output.join("").substr(0, 14));

        // e.g. 01/01/1992 ==> 9 chars
        // 01 / 01 / 1992 ==> 13 chars
        this.value = output.join("").substr(0, 14);
        prevInput = this.value;

        console.log(">>> this.value", this.value);
      };
    }

    // user typing
    date.addEventListener("input", wrapEventListener());
  </script>
</html>
...