我写了下面的代码行



$(".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弹出窗口的“确定”按钮后,当我们单击退格键时,它将不起作用。请帮忙!!!

最佳答案

1)在显示警告消息之前,应检查keyCode(del,退格键)。

if (event.which != 8 && event.which != 46  && $(this).val().length >= max_chars)


2)您应该将输入的重点放在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"
                        }).then(function() {
      										$(e.target).focus();
    										});

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

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

                    swal({
                        title: "Warning",
                        type: "warning",
                        text: "Number should not exceed 12 digits"
                     }).then(function() {
      									$(event.target).focus();
    								 });


                 $(this).val($(this).val().substr(0, max_chars));
               }
          });

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>

<input id ="driver_contact_number" class="only-numbers">

关于javascript - 单击swal的“确定”按钮后,退格键不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52890982/

10-10 18:35