Reputation: 670
I am trying to implement sweetalert2 but for some reason it doesn't apply regular html validation (i.e. required='true' isn't working), I am not getting an error that the field is empty.
Without swall2, it does prompt me with an error that the field is blank.
Also, once I confirm, in the swall dialog, that I want to proceed ("Yes, submit it!"), it does not submit the form.
What am I missing?
HTML:
<form>
<label>Last Name</label>
<input type="text" required="true"/>
<input class="btnn" type="submit" name="submit" id="btn-submit"/>
</form>
Javascript:
$('#btn-submit').on('click', function(e) {
e.preventDefault();
var form = $('form');
swal.fire({
title: "Are you sure?",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, submit it!",
closeOnConfirm: false
}, function(isConfirm) {
if (isConfirm) form.submit();
});
});
Upvotes: 2
Views: 6375
Reputation: 793
You can call swal on submit of form, currently on clicking on submit button swal confirm box called before form submit. JSFiddle Link : sweetalert Try below code :
$('#form1').on('submit',function(e){
e.preventDefault();
var form = $('form');
swal.fire({
title: "Are you sure?",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, submit it!",
closeOnConfirm: false
}, function(isConfirm){
if (isConfirm) form.submit();
});
});
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form name="form1" id="form1" method="post">
<label for="">Last Name</label><span class="required"> *</span>
<input type="text" required />
<input class="btnn" type="submit" name="submit" id="btn-submit"/>
</form>
</body>
</html>
Upvotes: 0
Reputation: 75
You can do this like that.
$('#btn-submit').on('click',function(e){
e.preventDefault();
var form = $('form');
console.log("hello");
swal.fire({
title: "Are you sure?",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, submit it!",
}).then(function (result){
if(result.value === true){
console.log("Submitted");
form.submit();
}
});
});
For more information you can look examples about SweetAlert2 from https://sweetalert2.github.io/#examples
Upvotes: 0
Reputation: 546
The documentation says after it has migrated to sweetalert2 the structure has changed from callback approach
swal(
{title: 'Are you sure?', showCancelButton: true}, function(isConfirm) {
if (isConfirm) {
// handle confirm
} else {
// handle all other cases
}
}
)
to promise based approach
Swal.fire({title: 'Are you sure?', showCancelButton: true}).then(result => {
if (result.value) {
// handle Confirm button click
// result.value will contain `true` or the input value
} else {
// handle dismissals
// result.dismiss can be 'cancel', 'overlay', 'esc' or 'timer'
}
})
Upvotes: 2