Form is submitted despite the warning message - javascript

I have a form (one text field and the submit button). The user input will be a 3-digit number and if the number is greater than 200 a warning will be displayed. If the user hits OK the form must be submitted but if he hits CANCEL then nothing happens and the user will be able to put some value again.
The fact is the my form is being submitted in any case (I can hardly notice the warning alert). Here is the code:
<form name="pontoi" action="update.php" method="post">
<div class="col-sm-4"><br>
<div class="input-group">
<input type="text" class="form-control" autofocus="autofocus" onkeyup="checkInput(this)" maxlength="3" id="points" name="points">
<span class="input-group-btn">
<button type="submit" id="prosthiki" onclick="checkInp(this)" class="btn btn-primary">ΠΡΟΣΘΗΚΗ</button>
</span>
</div>
</div>
</div>
</form>
function checkInp(e) {
var x = document.forms["pontoi"]["points"].value;
var y = 200;
if (x > y) {
sweetAlert({
title: "Number is over 200",
text: "Are you sure?",
type: "warning",
showCancelButton: true,
closeOnConfirm: false,
showLoaderOnConfirm: true,
});
} else {
return false;
}
}
If you have any ideas on what form is being submitted in any case it would help me a lot.
There is also this script (I think it is better to use) but It doesn't work too..
$('.btn btn-primary').on('click',function checkInp(e){
e.preventDefault();
var form = $(this).parents('pontoi');
swal({
title: "Number is over 200",
text: "Are you sure?",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "OK",
closeOnConfirm: false
}, function checkInp(isConfirm){
if (isConfirm) form.submit();
});
}
});

You have to listen also for the onsubmit event of the form.
Stopping the event propagation from the button has no effect.
What you could do is hook directly to the submit event and not the button click
document.querySelector("form").addEventListener("submit", function(ev){
var points = $("#points").val();
if(points > 200) {
// prevent form submission
// will be submitted if the user clicks ok
ev.preventDefault();
sweetAlert({
title: "Number is over 200",
text: "Are you sure?",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "OK",
closeOnConfirm: false
}, function checkInp(){
//ev.target is the form submitted
ev.target.submit();
});
}
})

Related

How do I use sweetalert2 with php form in CodeIgniter?

Details: How do I use sweetalert2 with PHP form in CodeIgniter?
Actually, I want to show sweetalert2 on submitting PHP form and then show sweetalert2 to confirm data, if the user confirms data should be submitted and then redirect to next page.
Problem: But in my case, it directly redirects to next page without my pressing confirm button on sweetalert.
PHP:
echo form_open( '/redirect to',['onsubmit'=>'return submitForm(this);']);
JavaScript:
function submitForm(){
swal({
title: "Are you Sure!",
text: "Data is Correct?",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#cc3f44",
confirmButtonText: "Yes!",
closeOnConfirm: false
}).then(okay => {
if(okay)
{
alert("check");
}
else
{
alert("not sure");
}
});
}
PHP
echo form_submit(['name'=>'submit','id'=>'submit','value'=>'Submit', 'class'=>'btn btn-primary btn_size' ]);
Please help me regarding this problem. thanks in advance.
I am posting my working code here.I deleted event by sweet alert It was mapped on button by giving a class name 'demo' to button hope it will help
$('.demo').click(function () {
//e.preventDefault();
var id= document.getElementById('id').value;
swal({
title: "Are you sure?",
text: "Your will not be able to recover this Event!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel plz!",
closeOnConfirm: false,
closeOnCancel: false },
function (isConfirm) {
if (isConfirm) {
location.href='<?php echo site_url('calendarController/delete_Event/'); ?>'+'/'+id;
} else {
swal("Cancelled", "Your event is safe :)", "error");
}
});
});

I try to implement Sweet Alert to Node.js delete form

I'm trying to implement Sweet Alert to Node.js delete form, but unfortunately the alert doesn't work properly. It only pops up for a second and without clicking on delete button on the alert window, it deletes file from DB.
Here is my code:
<form action="/comicbooks/<%= comicbook._id %>/?_method=DELETE"
method="POST" class="deleteForm" onsubmit='swal({
title: "Are you sure?",
text: "Your will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonClass: "btn-danger",
confirmButtonText: "Yes, delete it!",
closeOnConfirm: false,
showLoaderOnConfirm: true,
},
function (isConfirm) {
location.reload();
});'>
<button class="btn btn-xs btn-danger">Delete</button>
</form>
Coul you please assist?
Many thanks in advance,
Szymon
You have two problems.
When the submit button is clicked, you want to display the alert, but you don't want the form to submit. You've done nothing to prevent the form from submitting.
When the alert has the OK button clicked, you want to submit the form, but you are reloading the current page instead.
So, sort out the submit button first.
Don't use the onsubmit attribute. It is more trouble than it is worth.
document.querySelector("form").addEventListener("submit", function (event) {
event.preventDefault(); // Stop normal form submitting
// Then include your code for showing the alert
});
Then make the alert do what you want when the OK button is selected.
function (isConfirm) {
document.querySelector("form").submit();
})
I finally found a bug in above code and now it is working perfectly in EJS file. There should be:
function archiveFunction(event) {
event.preventDefault(); // prevent form submit
var form = event.target.form; // storing the form
swal({
title: "Are you sure you want to delete the comicbook?",
text: "You will not be able to undo this action.",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Delete",
cancelButtonText: "Cancel",
closeOnConfirm: false,
closeOnCancel: false
},
function (isConfirm) {
if (isConfirm) {
form.submit(); // submitting the form when user press yes
} else {
swal("Cancelled", "Your comicbook has not been deleted.", "error");
}
});
}
Cheers,
Szymon

Sweet Alert 2 confirmation before submit

I'm trying to make a confirmation pop up before submitting the form. But it's not working. I'm using Sweet Alert 2.
document.querySelector('#order').addEventListener('submit', function(e) {
var form = $(this).parents('form');
e.preventDefault();
swal({
title: "Are you sure?",
text: "Once a invoice is created, you will not be able to delete without the help of support",
type: "warning",
showCancelButton: true,
confirmButtonColor: '#DD6B55',
confirmButtonText: 'Yes, I am sure!',
cancelButtonText: "No, cancel it!",
}).then(function() {
swal({
title: 'Success!',
text: 'Invoice created! Go to the invoice tab to pay it.',
type: 'success'
}, function() {
form.submit();
});
},function(dismiss) {
if(dismiss == 'cancel') {
swal("Cancelled", "Invoice not created!", "error");
}
});
});
That's my Javascript code and my PHP code looks something like this
<?php
if(isset($_POST['k'])
{
header('Location: https://google.com');
}
?>
My HTML code is
<form method="POST">
<button type="submit" name="k"></button
</form>
It's not working why?
Update
$("#order").on('submit', function(e) {
var form = $(this);
e.preventDefault();
swal({
title: "Are you sure?",
text: "Once a invoice is created, you will not be able to delete without the help of support",
type: "warning",
showCancelButton: true,
confirmButtonColor: '#DD6B55',
confirmButtonText: 'Yes, I am sure!',
cancelButtonText: "No, cancel it!",
}).then(function() {
swal({
title: 'Success!',
text: 'Invoice created! Go to the invoice tab to pay it.',
type: 'success'
}, function() {
$(this).trigger('submit');
});
},function(dismiss) {
if(dismiss == 'cancel') {
swal("Cancelled", "Invoice not created!", "error");
}
});
});
Also I forgot to add that I parsed that code and on my actual code there is the ID on the form
By not working I mean the data isn't being posted. If it was working properly, it should be redirecting to google.com per the PHP code
I am no coder but I found that placing the submit under .then(function() { was a working solution for me. The code I used is lp.jQuery("div.main-form form").submit(); but your form name will be different. I hope it helps in some way.
$("#order").on('submit', function(e) {
var form = $(this);
e.preventDefault();
swal({
title: "Are you sure?",
text: "Once a invoice is created, you will not be able to delete without the help of support",
type: "warning",
showCancelButton: true,
confirmButtonColor: '#DD6B55',
confirmButtonText: 'Yes, I am sure!',
cancelButtonText: "No, cancel it!",
}).then(function() {
$(this).trigger('submit');
swal({
title: 'Success!',
text: 'Invoice created! Go to the invoice tab to pay it.',
type: 'success'
}, function() {
$(this).trigger('submit');
});
},function(dismiss) {
if(dismiss == 'cancel') {
swal("Cancelled", "Invoice not created!", "error");
}
});
});
First, you don't have the selector #order in this HTML.
Second, you'll want to prevent the default behavior of the form element, so do this:
$("form").on('submit', function(e) {
var form = $(this);
e.preventDefault();
//[...]
Then, where you want to finally submit, you can put this:
$(this).trigger('submit');

Getting element Id Sweet Alert

I'm trying to use sweet alert as a dialog to confirm the deletion of an entry on a table.
There's a column on each table row which has a button which opens a 'Sweet Alert' confirm dialog.
The code of my table is as follow:
<tr>
<!-- Other Table Colums -->
<td>
<button userid="<?php echo $row['id']; ?>" id="<?php echo('bn_delete_' . $row['id']); ?>" class="btn btn-danger btn-xs warning-message-parameter">Delete</button>
<td>
</tr>
The code for my sweet alert dialog is:
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"); });
When the user clicks yes on the dialog, I want to get the id of the button which the user just clicked. That way I'll be able to get the value of the attribute userid which I can then use to delete the entry from database.
You can get the id of the clicked button by retrieving it when the button is clicked, and passing it as a parameter to the plugin callback.
Take a look at the following implementation:
$('#openSwal').on('click', function(e) {
var id = $(e.currentTarget).attr("id");
var userId = $(e.currentTarget).data("user-id");
var region = "myregion";
swal({
html: true,
title: '' + region,
showCancelButton: true,
showConfirmButton: true,
confirmButtonText: "save",
text: "<span onclick='save()'>l</span>"
}, function() {
save(id, userId);
});
});
function save(id, userId) {
console.log(id);
console.log(userId);
}
http://jsfiddle.net/jwsho9L9/4/

Page is not waiting for response from SweetAlert confirmation window

I am trying to upgrade my JavaScript confirm() action to use SweetAlert. Currently my code is something like this:
<a href="/delete.php?id=100" onClick="return confirm('Are you sure ?');" >Delete</a>
This waits for the user to confirm before navigating to the delete page. I would like to use this example from SweetAlert to ask the user to confirm before deleting:
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) {
swal("Deleted!", "Your imaginary file has been deleted.", "success");
}
else {
swal("Cancelled", "Your imaginary file is safe :)", "error");
}
});
Everything I have tried has failed. When the first alert is displayed, the page has gone ahead and deleted the item and refreshed before the user has even clicked on the alert buttons. How do I make the page wait for the users input?
Any help would be greatly appreciated.
You cannot use this as a drop-in replacement for confirm. confirm blocks the single thread of execution until the dialog has been acknowledged, you cannot produce the same behavior with a JavaScript/DOM-based dialog.
You need to issue a request to /delete.php?id=100 in the success callback for your alert box.
Instead of...
swal("Deleted!", "Your imaginary file has been deleted.", "success");
You need
<a href="#">Delete<a>
...
$.post('/delete.php?id=100').then(function () {
swal("Deleted!", "Your imaginary file has been deleted.", "success");
});
You also must fix your delete.php to only accept POST requests. It's a huge problem to allow GET requests to delete resources. The first time Google or any other crawler finds your page, it will look at the href of every link in your document and follow each link, deleting all of your content. They will not be stopped by the confirm box, as they probably (with the exception of Google) won't be evaluating any JavaScript.
You can do it this way.
HTML:
<a href="/delete.php?id=100" class="confirmation" >Delete</a>
JS:
$('.confirmation').click(function (e) {
var href = $(this).attr('href');
swal({
title: "Are you sure?",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel plx!",
closeOnConfirm: true,
closeOnCancel: true
},
function (isConfirm) {
if (isConfirm) {
window.location.href = href;
}
});
return false;
});
Seems a hack but it's working for me.
$('.delete').click(function () {
var id = this.id;
swal({
title: "Are you sure?",
text: "Your will not be able to recover this post!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
closeOnConfirm: false
},
function(){
alert(id);
});
});
<a id="<?php echo $row->id_portfolio ?>" class=" delete">
Here's an example in an Angular directive (since SweetAlert is offered through an angular directive wrapper). This is one 'elegant' method for doing this in JavaScript. On a click event, there is an e.stopImmediatePropagation(), then if the user confirms, it evaluates the "ng-click" function. (Note scope.$eval is not a JavaScript eval()).
Markup:
<i class="fa fa-times" ng-click="removeSubstep(step, substep)" confirm-click="Are you sure you want to delete a widget?"></i>
Simple "confirm click" directive:
/**
* Confirm click, e.g. <a ng-click="someAction()" confirm-click="Are you sure you want to do some action?">
*/
angular.module('myApp.directives').directive('confirmClick', [
'SweetAlert',
function (SweetAlert) {
return {
priority: -1,
restrict: 'A',
link: function (scope, element, attrs) {
element.bind('click', function (e) {
e.stopImmediatePropagation();
e.preventDefault();
var message = attrs.confirmClick || 'Are you sure you want to continue?';
SweetAlert.swal({
title: message,
type: 'warning',
showCancelButton: true,
closeOnConfirm: true,
closeOnCancel: true
}, function (isConfirm) {
if (isConfirm) {
if(attrs.ngClick) {
scope.$eval(attrs.ngClick);
}
} else {
// Cancelled
}
});
});
}
}
}
]);

Categories

Resources