Reputation: 207
im new using sweet alert, first i will show the code :
$('#byr').keydown(function (e){
var bayar = Number($('#byr').val());
var total = Number($('.rp-harga').text());
var kmb = $('.rp-kmb').text();
if(e.keyCode == 13)
{
if(bayar<total)
{
alert("Uang Anda Kurang");
}
else {
swal("Transaksi Berhasil", "Kembalian : Rp " + (bayar-total).toString(), "success");
}
}
});
The problem is when i hit enter after fill the input text with else condition, it will show the sweet alert, but the sweet alert will immidiately closed before i click OK button or hit enter when sweet alert appear
I tried adding e.preventDevaults()
, and get these problem :
Here is a working JSFiddle with my problem.
Upvotes: 1
Views: 7601
Reputation: 42044
I assume you are using sweetalert2. This plugin has a configuration option:
allowEnterKey: If set to false, the user can't confirm the modal by pressing the Enter or Space keys, unless they manually focus the confirm button.
Therefore you can:
call swal after 10 milliseconds in order to overcome the following src code for the first keydown:
window.onkeydown = handleKeyDown;
$('#byr').keydown(function (e) {
var bayar = Number($('#byr').val());
var total = 0;
if (e.keyCode == 13) {
if (bayar < total) {
alert("Uang Anda Kurang");
}
else {
setTimeout(function() {
swal({
title: "Transaksi Berhasil",
text: "Kembalian : Rp " + (bayar - total).toString(),
type: "success",
allowEnterKey: true // default value
});
}, 10)
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/sweetalert2/6.6.2/sweetalert2.min.css">
<script src="https://cdn.jsdelivr.net/sweetalert2/6.6.2/sweetalert2.min.js"></script>
<input type="text" id="byr">
Upvotes: 6