Sweetalert - validation isn't working + form is not submitting - javascript

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?
JSfiddle
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();
});
});

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'
}
})

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

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>

Related

Cannot submit form using jquery

I have a problem at submitting a form within sweetalert2 using jquery.
Here's the code that i have:
<?=form_open_multipart('controller_path','id="form_service"' , ''?>
<input type="button" name="update" id="submit-operate" value="Submit To Operated" class="btn btn-success" onclick="service.submitService()"/>
<?= form_close(); ?>
and this is service.js:
submitService: function(){
swal({
title: 'Are you sure?',
text: "You will submit this service to the next phase",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Submit'
}).then((result) => {
if (result.value) {
$("#form_service").submit()
}
});
}
The sweetalert works as well, and when I do the console.log in if(result.value) it shows on the console, but the form doesn't submit. Can somebody show me the correct way? Thank you.
Try this:
submitService = function(){
var form = $("#form_service");
swal({
title: 'Are you sure?',
text: "You will submit this service to the next phase",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Submit'
}).then((result) => {
if (result.value) {
form.submit(); //semicolon in the end
}
});
}

SweetAlert with Java Servlet

I wanted to pause form's onsubmit, so I could ask user to confirm action before proceed.
So here's my form:
<form action="<%= request.getContextPath()%>/Controller"
method="POST" id="remove_book"
onsubmit="alertBookInfo('return_book')">
</form>
Then, I created the JavaScript function, using SweetAlert:
function alertInfo(action) {
document.querySelector(action).addEventListener('submit', function (e) {
var form = this;
e.preventDefault();
if (action === "remove_book") {
swal({
title: "Remove book?",
text: "Watch out",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes.",
cancelButtonText: "No.",
closeOnConfirm: false,
closeOnCancel: false
},
function (isConfirm) {
if (isConfirm) {
swal({
title: "Deleted.",
text: "Done.",
type: "success"
}, function () {
form.submit();
});
} else {
swal("Cancelled", "Not done.", "error");
}
});
}
});
}
But for some reason, I am unable to prevent page reload on form submit. Am I doing someting wrong?
PS: I already tried with return alertInfo() in form and returning boolean value from JS function with no success.
Why not call the function from the form like this, the the alert will be prompt before submitting the form:
HTML
<form action="<%= request.getContextPath()%>/Controller" method="GET" id="remove_book" onclick="myAlertFunction(event)">
<input type="submit">
</form>
JavaScript
function myAlertFunction(event) {
event.preventDefault()
swal({
title: "Remove book?",
text: "Watch out",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes.",
cancelButtonText: "No.",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm) {
if (isConfirm) {
swal({
title: "Deleted.",
text: "Done.",
type: "success"
}, function() {
$("#remove_book").submit();
});
} else {
swal("Cancelled", "Not done.", "error");
}
});
}
And if you want to prevent the reload, you can always use event.preventDefault()
Here is an example: JSFiddel
If you don't want the page reloads you could use an AJAX call. When you use the submit() you will always reload the page because is how submit works.
$.ajax({
method: "POST",
url: YOUR_ACTION_URL,
data: $('form').serialize(),
success: function(data){
//here you could add swal to give feedback to the user
}
});
In your controller you have to define the method as produces JSON, if you are using Spring, the annotation is #ResponseBody

How to run a SweetAlert instead of default javascript confirm method

Currently this is the code I use to run a normal confirm window based on the class "confirmation". This is all done with an href link and not on a button onClick event. As the result of the click is to run another code snipped placed in a different file (with the intention to delete a row in db).
$('.confirmation').on('click', function () {
return confirm('Er du sikker på at du vil slette?');
});
What I want is to replace the confirm method with this SweetAlert function
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
closeOnConfirm: false
}, function(){
swal("Deleted!", "Your imaginary file has been deleted.", "success");
});
Anyone know how to do this, what happens when I try to place the sweetalert inside the onClick function is that the alert appears but it automatically delete the row without me having to confirm anything and the alert fades out.
I found the solution!
$('.confirmation').click(function(e) {
e.preventDefault(); // Prevent the href from redirecting directly
var linkURL = $(this).attr("href");
warnBeforeRedirect(linkURL);
});
function warnBeforeRedirect(linkURL) {
swal({
title: "Leave this site?",
text: "If you click 'OK', you will be redirected to " + linkURL,
type: "warning",
showCancelButton: true
}, function() {
// Redirect the user
window.location.href = linkURL;
});
}
I made this codepen in case anyone wants to debug. It appears this is working (check the browser console log for when 'done' is printed)
http://codepen.io/connorjsmith/pen/YXvJoE
$('.confirmation').on('click', function(){
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel plx!",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm){
if (isConfirm) {
console.log('done');
swal("Deleted!", "Your imaginary file has been deleted.", "success");
} else {
swal("Cancelled", "Your imaginary file is safe :)", "error");
}
});
})
Add event.preventDefault(); preventDefault();
$('.confirmation').on('click', function (event) {
event.preventDefault();
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
closeOnConfirm: false
}, function(){
swal("Deleted!", "Your imaginary file has been deleted.", "success");
});
});
Try this code which is mentioned as in docs:
$('.confirmation').on('click', function () {
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
closeOnConfirm: false
}, function(isConfirm){
return isConfirm; //Will be either true or false
});
});
I wrote this function:
function sweetConfirm(title, text) {
event.preventDefault();
var target = $(event.target);
var href = null;
var form = null;
if (target.is("a")) href = target.attr("href");
else if (target.is("button:submit")) form = target.closest("form");
else if (target.is("button")) href = target.attr("href") || target.attr("value");
swal({
title: title,
text: text,
type: "warning",
allowOutsideClick: true,
showCancelButton: true
}, function () {
if (href) window.location.href = href;
else if (form) form.submit();
});
}
sweetConfirm function will accept a submit button, link button or a normal button and will ask before do the action.
You can use it in the following scenarios:
<a type="button" class="btn btn-default" href="/" onclick="return sweetConfirm('Are you sure?')">
Link Button 1
</a>
<button type="button" class="btn btn-default" href="/" onclick="return sweetConfirm('Are you sure?')">
Link Button 2
</button>
<form action="/" method="DELETE">
<input type="hidden" name="id" value="..">
<button type="submit" class="btn btn-danger" onclick="return sweetConfirm('Are you sure?')">
Delete
</button>
</form>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/sweetalert2#7.32.4/dist/sweetalert2.min.css">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2#7.32.4/dist/sweetalert2.all.min.js"></script>
</head>
<body>
<a id="confirmation" href="test">Test</a>
<script type="text/javascript">
$('#confirmation').click(function(e) {
e.preventDefault(); // Prevent the href from redirecting directly
var linkURL = $(this).attr("href");
console.log(linkURL)
warnBeforeRedirect(linkURL);
});
function warnBeforeRedirect(linkURL) {
Swal({
title: 'sAre you sure?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then((result) => {
if (result.value) {
window.location.href = linkURL;
}
})
}
</script>
</body>
</html>

JavaScript Confirmation form Message

I have a confirmation message in my form with JS script but the value of "verif" always false or I do not know where is the problem; If I boot "verif" with false, it's still false
function valider() {
var verif = false;
swal({
title: "Are you sure?",
text: "You will not be able to recover this file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel plx!",
closeOnConfirm: false,
closeOnCancel: false
}, function(isConfirm) {
if (isConfirm) {
swal("Deleted!", "Your file has been deleted.", "success");
verif = true;
alert("afficher");
} else {
swal("Cancelled", "Your file is safe :)", "error");
verif = false;
swal("afficher");
}
});
if (verif) {
$("#formulaire").submit();
}
return false;
}
$("#envoyer").click(function() {
valider();
return false;
});
and this is the HTML Code
<form action="archi.php" method="post" class="form-horizontal" id="formulaire">
<div class="form-actions">
<button type="submit" id="envoyer" class="btn blue envoyer"> <i class="icon-save"></i> Archiver</button>
<button type="button" class="btn">Cancel</button>
</div>
</form>
Why do you add another test for submitting? Add submit to the callback function and delete additional if:
function valider() {
var verif = false;
swal({
title: "Are you sure?",
text: "You will not be able to recover this file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel plx!",
closeOnConfirm: false,
closeOnCancel: false
}, function(isConfirm) {
if (isConfirm) {
$("#formulaire").submit();
swal("Deleted!", "Your file has been deleted.", "success");
} else {
swal("Cancelled", "Your file is safe :)", "error");
swal("afficher");
}
});
return false;
}
$("#envoyer").click(function() {
valider();
return false;
});
P.S. Try adding a console.log() before the return from verif() function to check if the }, function(isConfirm) { is async (this would clarify all misunderstanding).

How To Use Sweet alert

This Is My HTML Code
I Have Two Input Button That I Want To Show Sweet Alert When a user Clicks on any Button
<tr class="examples odd" id="UserId_1" role="row">
<td class="sorting_1">1</td>
<td>admin</td><td>Mohammad</td>
<td>Farzin</td><td class="warning"><input type="button"
value="Delete" class="sweet-5" id="btn_Delete1"></td>
</tr>
<tr class="examples even" id="UserId_5" role="row">
<td class="sorting_1">2</td>
<td>11</td><td>11</td>
<td>11</td><td class="warning"><input type="button" value="Delete" class="sweet-5"
id="btn_Delete5"></td>
</tr>
Script
$(document).ready(function () {
document.querySelector('td.warning input').onclick = function () {
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonClass: 'btn-danger',
confirmButtonText: 'Yes, delete it!',
cancelButtonText: "No, cancel plx!",
closeOnConfirm: false,
closeOnCancel: false
},
function (isConfirm) {
if (isConfirm) {
swal("Deleted!", "Your imaginary file has been deleted!", "success");
} else {
swal("Cancelled", "Your imaginary file is safe :)", "error");
}
});
};
});
Only The First Input Button Shows Sweet Alert, but
when I click the second button nothing happens
You were probably using SweetAlert version 2 and your code applies to version 1.
This should work:
swal({
title: 'Are you sure?',
text: 'Some text.',
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#DD6B55',
confirmButtonText: 'Yes!',
cancelButtonText: 'No.'
}).then(() => {
if (result.value) {
// handle Confirm button click
} else {
// result.dismiss can be 'cancel', 'overlay', 'esc' or 'timer'
}
});
<script src="https://unpkg.com/sweetalert2#7.8.2/dist/sweetalert2.all.js"></script>
Source:
Migration from Swal1 to Swal2
Try this
$(document).ready(function () {
$('body').on('click', 'td.warning input', function () {
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonClass: 'btn-danger',
confirmButtonText: 'Yes, delete it!',
cancelButtonText: "No, cancel plx!",
closeOnConfirm: false,
closeOnCancel: false
},
function (isConfirm) {
if (isConfirm) {
swal("Deleted!", "Your imaginary file has been deleted!", "success");
} else {
swal("Cancelled", "Your imaginary file is safe :)", "error");
}
});
});
});
Check Fiddle
http://jsfiddle.net/hoja/5a6x3m36/5/
If you want sweet alert on click of any button then change your code like below:
$(document).ready(function(){
$(document).on('click', 'button', function(){
Swal.fire({
type: 'success',
title: 'Your work has been done',
showConfirmButton: false,
timer: 1500
})
});
});
with sweet alert it is more easy for example i fave a link what i need is to call onclick function and make sure i included sweetalser.css and sweetalert.min.js i hope this will work for you
<a onclick="sweetAlert('Greetings', 'Hi', 'error');" class="" data-toggle="modal" href='#modale-id'><i class="fa fa-fw fa-plus"></i>Streams</a>
You are only selecting the first element that matches 'td.warning input' selector, that's why nothing happens to the second element.
Try querySelectorAll('td.warning input') method.
This returns an array and you can loop through the array to set Event Listeners.
window.onload=function()
{
swal({ title: "PopOutTitle", text: "Your FIRST Name:", type: "input", showCancelButton: true, OnConfirm:school();
animation: "slide-from-top", inputPlaceholder: name }, function(inputValue){ if (inputValue === false) return false;
if (inputValue === "") { swal.showInputError("You need to write something!"); return false }
document.getElementById("name").innerHTML=inputValue || "Unknown";
});
}
function school(){
swal({ title: "PopOutTitle", text: "Your last Name:", type: "input", showCancelButton: true,
animation: "slide-from-top", inputPlaceholder: name }, function(inputValue){ if (inputValue === false) return false;
if (inputValue === "") { swal.showInputError("You need to write something!"); return false }
document.getElementById("name").innerHTML=inputValue || "Unknown";
});**I want to show multiple swal popout so I want to call the school function when Ok Button is clicked. How can I do this?**
<script>
$(document).ready(function(){
$('.btn-danger').on("click", function(){
swal({
title: "Delete?",
text: "Please ensure and then confirm!",
type: "warning",
showCancelButton: !0,
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel!",
reverseButtons: !0
}).then(function (e) {
if (e.value === true) {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
var id = $('.btn-danger').attr('data-id');
var cur_row = this;
$.ajax({
type: 'POST',
url: "{{url('/product_delete')}}/" + id,
data: {_token: CSRF_TOKEN},
dataType: 'JSON',
success: function (results) {
if (results.success === true)
{
swal("Done!", results.message, "success");
setTimeout(function(){
location.reload()
}, 2000);
}
else
{
swal("Error!", results.message, "error");
}
}
});
}
});
});
});
</script>
/* Add link in head section */
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.2.0/sweetalert2.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.2.0/sweetalert2.all.min.js"></script>
The Below examples are taken from https://sweetalert2.github.io/.
Get the latest version of sweetalter2 from here https://www.bootcdn.cn/limonte-sweetalert2/
Displaying validation error
<!DOCTYPE html>
<html>
<head>
<title>Testing</title>
<script src="https://cdn.bootcdn.net/ajax/libs/limonte-sweetalert2/11.7.0/sweetalert2.all.js"></script>
</head>
<body>
<script>
Swal.fire({
icon: 'error',
title: 'Validation Error!!!',
text: 'Passwords Did not Match!',
footer: 'Why do I have this issue?'
})
</script>
</body>
</html>
Display custom html
<!DOCTYPE html>
<html>
<head>
<title>Testing</title>
<script src="https://cdn.bootcdn.net/ajax/libs/limonte-sweetalert2/11.7.0/sweetalert2.all.js"></script>
</head>
<body>
<script>
Swal.fire({
title: '<strong>HTML <u>example</u></strong>',
icon: 'info',
html:
'You can use <b>bold text</b>, ' +
'links ' +
'and other HTML tags',
showCloseButton: true,
showCancelButton: true,
focusConfirm: false,
confirmButtonText:
'<i class="fa fa-thumbs-up"></i> Great!',
confirmButtonAriaLabel: 'Thumbs up, great!',
cancelButtonText:
'<i class="fa fa-thumbs-down"></i>',
cancelButtonAriaLabel: 'Thumbs down'
})
</script>
</body>
</html>

Categories