我在下面的代码行中写过
$(".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弹出窗口的“确定”按钮后,当我们单击退格键时,它将不起作用。请帮忙!!!
答案 0 :(得分:1)
1)在显示警告消息之前,应检查keyCode(删除键,退格键)。
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">
答案 1 :(得分:1)
解除警报后,您可以利用承诺将注意力集中在您的来源。
其他更改:
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">
答案 2 :(得分:0)
很难给出准确的例子,但我想说的是,当您单击警报的“确定”按钮时,您的输入不再集中,因此退格键无效。
您可以通过在单击“确定”后将焦点设置为输入来解决此问题(文档中有一些方法如swal.DismissReason.close:https://sweetalert2.github.io/#handling-dismissals)