首页 > 解决方案 > 单击 swal 的确定按钮后退格键不起作用

问题描述

我在下面写了几行代码

$(".only-numbers").keypress(function(e) {
  if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
    swal({
      title: "Warning",
      type: "warning",
      text: "Please enter Numbers only"
    });

    return false;
  } else {
    return true;
  }
});

$("#driver_contact_number").on("keyup keydown change", function(event) {
  var max_chars = 12;
  if ($(this).val().length >= max_chars) {

    swal({
      title: "Warning",
      type: "warning",
      text: "Number should not exceed 12 digits"
    });


    $(this).val($(this).val().substr(0, max_chars));
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.0/sweetalert.min.js"></script>
<input id="driver_contact_number" class="only-numbers">

每当用户输入大于 12 位时,就会显示 swal 警告消息,但是在单击 swal 弹出窗口的 ok 按钮后,当我们单击退格时,它不起作用。请帮忙!!!

标签: javascriptjquerysweetalert

解决方案


解除警报后,您可以利用承诺重新关注您的来源。

其他变化:

  • 我不知道为什么你有 else ,但我在不需要时删除了它。
  • 你有一个弃用的type所以我把它改成icon
  • 您的长度函数有 >= 但应该是 > 导致退格问题

$(".only-numbers").on('keypress', function(e) {
  if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
    swal({
      title: "Warning",
      icon: "warning",
      text: "Please enter Numbers only"
    }).then(function() {
      $(e.target).focus();
    });
    return false;
  }
  return true;
});

$("#driver_contact_number").on("keyup keydown change", function(event) {
  var max_chars = 12;
  if ($(this).val().length > max_chars) {
    swal({
      title: "Warning",
      icon: "warning",
      text: "Number should not exceed 12 digits"
    }).then(function() {
      $(event.target).focus();
    });
    $(this).val($(this).val().substr(0, max_chars));
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.0/sweetalert.min.js"></script>
<input id="driver_contact_number" class="only-numbers">


推荐阅读