javascript - 无法使用javascript以自动格式删除

标签 javascript algorithm date date-formatting

1.

这里是 original auto format date别人做的,

因此日期类似于 12/12/2019,我们使用 space/space 来分隔数字。

2.

我想使用类似12/12/2019 的格式,但似乎无法删除。

This is the code pen I have

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>

最佳答案

在原来的笔中,斜线之间有一个空格。所以当用户删除一个空格时,我们可以检查最后一个字符是否是“/”并删除之前的字符。

在你的情况下没有空间。在任何时候,您的更改监听器都会以最后一个字符作为数字被调用。

所以你不能使用这种方法。在这种情况下,我会建议,跟踪以前的值并使用它来删除“/”之前的字符。

示例 如果 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>

关于javascript - 无法使用javascript以自动格式删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58212245/

相关文章:

r - 在 R 中将字符串转换为日期会返回 NA

javascript - 删除iframe会导致内存泄漏吗?

javascript - 用按钮替换浏览器滚动条

javascript - 如何在json2html中使用onclick

python - 蛋白质序列模式匹配python

php - 我在 php 中寻找比 substr_count($string, $needle, $offset, $length) 更好的算法复杂度

Java日期解析错误地增加了一个小时

php - 如果某些列数据与原始查询不准确,如何阻止其显示?

javascript - 使用 `CanvasRenderingContext2D.putImageData()` 时出现白屏,即使数据似乎包含图像

algorithm - 为什么将 "Algorithms"和 "Data Structures"视为不同的学科?