somebody knows how to submit a form in html with sweetalert?
I have this checkbox and I want that onchange "direct" me to the sweetalert js with 2 Buttons. One with "No" and one with "Yes". The "Yes" button should now be the new "onchange" and with the "No" button the submit should be canceled.
<form method='post' action='....'>
<input type="checkbox" name="checkbox_admin" onchange="submit();" checked>
</form>
Hope you know what I mean. :D
This is how I would normally do
$(document).ready(function() {
$('[data-click="swal-danger"]').click(function(e) {
e.preventDefault();
var form = $(this).parents('form');
swal({
title: "Are You Sure?",
text: "Are You Sure You Want To Delete.",
icon: "error",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
swal(form.submit(), {
icon: "success",
});
} else {
}
});
});
});
Use this while submitting the form via swal/Sweetalert
swal(form.submit()
Then create a form submit button but without the type submit as bellow
<form method='post' action='....'>
<button class="btn btn-danger" data-click="swal-danger">DELETE USER</button>
</form>
Make sure your button have this on your button data-click="swal-danger"
Related
This code should perform the following when clicked:
submit the form
disable the button to prevent double clicks
add a spinner to the button to notify the user something is happening
if the form is invalid, stop the form submission, remove the spinner, and enable the button.
While writing this code, I found that it will perform validation and form submission only when the button type is set to submit. If the button type is button, the form.submit in the button click event does not submit the form. Processing of the form halts, no validation occurs, no form submission. I set up break points inside the jquery #myForm.submit, and they are never hit. Does anyone have an explanation for this behavior?
frameworks: jquery 3.4.1, bootstrap 4
<form action="doSomething" id="myForm">
...
<!-- this performs validation and submits the form -->
<button type="submit" id="aButton" class="btn btn-primary" data-validate="true">
Save
</button>
<!-- this does not perform validation nor submits the form -->
<button type="button" id="bButton" class="btn btn-primary" data-validate="true">
Save
</button>
</form>
Javascript
removeSpinnerFromButton = function (btn) {
var span = btn.find('span[id="spinner"]');
span.remove();
btn.removeAttr('disabled');
btn.removeClass('cursor-wait');
};
addSpinnerToButton = function (btn) {
btn.attr('disabled', 'disabled');
btn.addClass('cursor-wait');
$("<span/>", {
class: 'spinner-border spinner-border-sm',
id: 'spinner',
role: 'status',
aria_hidden: 'true'
}).appendTo(btn);
};
$('button[data-validate="true"]').click(function () {
var $self = $(this);
$('#myForm').submit(function (event) {
addSpinnerToButton($self);
if ($(this).valid()) {
return true;
} else {
event.preventDefault();
removeSpinnerFromButton($self);
return false;
}
});
});
Edit
this bit of code aides in understanding what is happening.
$(function(){
$('#myInputSubmit').click(function(){alert('input of type submit clicked');});
$('#myInputButton').click(function(){alert('input of type button clicked');});
$('#myButtonSubmit').click(function(){alert('button of type submit clicked');});
$('#myButtonButton').click(function(){alert('button of type button clicked');});
$('form').submit(function(e){alert('form submitted');e.preventDefault();});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="button" id="myInputButton" value="input button" />
<input type="submit" id="myInputSubmit" value="input submit" />
<button type="button" id="myButtonButton">button button</button>
<button type="submit" id="myButtonSubmit">button submit</button>
</form>
input or button type="submit" has a default behaviour: Submit the form
button type="button" (or no type at all) doesn't have a default behaviour and you should add it with a listener, as you're already doing for click event. Inside that function you should validate and, if it's the case, submit the form with $('#myForm').submit();, with no params
With this piece of code, you're adding a submit listener to the form instead of submit it:
$('#myForm').submit(function (event) {
addSpinnerToButton($self);
if ($(this).valid()) {
return true;
} else {
event.preventDefault();
removeSpinnerFromButton($self);
return false;
}
});
When button is clicked, do your validations and then submit the form. Right now, you need a plugin to validate with $(this).valid(), otherwise, an error will be thrown.
$('button[data-validate="true"]').click(function () {
var $self = $(this);
addSpinnerToButton($self);
if ($(this).valid()) {
$('#myForm').submit();
} else {
removeSpinnerFromButton($self);
}
});
I am trying to do the following.
I have 3 buttons, "Continue", "Delete", "New". All of these are type "submit" buttons.
When the form is posted, the value of these buttons is used to determine what happens on the backend.
I want a Sweetalert popup to confirm if the user wants to delete, then when the OK button is hit, the form should progress and submit to the backend.
The issue I currently have is that there is no way to get the value of the submit button to the server side when I incorporate Sweetalert to show when I hit the submit button.
Scenario A) For example, if I remove the "e.preventDefault" from the callback, the alert popups for a brief second but the form submits, not giving the user to confirm or cancel the deletion. This is not correct behaviour, but the "submit" button value does indeed get posted to the server. So to prevent the quick popup issue, I add "e.preventDefault" to stop the normal behaviour of "submit" button.
Scenario B) However, when I have the code as below (i.e. "e.preventDefault" added to the code), the form does not submit after validation. Instead I have to run "$('#myForm').submit()". But when I do this, the value of the "submit" button does not get posted to the server.
If someone could kindly guide me on how I can use jQuery Validate and Sweetalert, it would be much appreciated.
An example of the set up looks like this:
HTML:
<script src="https://cdn.jsdelivr.net/npm/jquery-validation#1.17.0/dist/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js"></script>
<form id="myForm" action="/postHere" method="post">
<!-- Options-->
<div class="row-select">
<label for="options">My Options</label>
<select name="options" id="options">
<option disabled="true" selected="selected">Select an Option</option>
<option value="a">a</option>
<option value="b">b</option>
</select>
</div>
<!-- continue details form -->
<div>
<input type="submit" id="continue" name="submitButton" value="Continue this Option">
</div>
<!-- delete details -->
<div>
<input class="delete" type="submit" id="delete" name="submitButton" value="Delete this Option">
</div>
<!-- new -->
<div class="row-spaced">
<input type="submit" id="submitButton" name="submitButton" value="Neither" formnovalidate>
</div>
</form>
Javascript:
function myFunction() {
var continueOption = document.getElementById('continue');
var deleteOption = document.getElementById('delete');
var neither = document.getElementById('new');
$('#myForm').validate({
ignore:'',
rules: {
options: "required"
},
});
// AIM IS TO SHOW A CONFIRMATION BOX IF DELETE IS CLICKED
if(deleteOption) {
deleteOption.addEventListener("click", function(e) {
e.preventDefault();
swal({
title: "Are you sure?",
text: "Once deleted, you will not be able to recover this imaginary file!",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
console.log("here");
$('#myForm').submit();
}
});
});
}
}
myFunction();
Backend Illustration:
router.post("/postHERE", (req, res) => {
if (req.body.submitButton == "Continue this Option") {
// Do something CONTINUE
}
else if (req.body.submitButton == "Delete this Option") {
// Do something DELETE
}
else {
// Do something NEW
}
}
JSFiddle:
JSFiddle Example
EDIT:
For the backend I am using Expressjs. I have added this in and fixed a type in the form method to be post.
This is my Form :
<form class="myForm" action="/videos/{{ $video->uid }}" method="post">
Edit
<button type="button" class="btn btn-danger delete">Delete</button>
{{ csrf_field() }}
{{method_field('DELETE')}}
</form>
Here is the js with sweetalert :
$('.delete').on('click', function(){
swal({
title: "Are you sure?",
text: "You will not be able to recover this lorem ipsum!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
closeOnConfirm: false
},
function(){
$(".myForm").submit();
});
})
This always deletes the last row from the page i.e it takes the last value on the page and deletes even if we selected some other value
But this code works:
$(".myForm").on("submit", function(){
return confirm("Do you want to delete this item?");
});
Since it does not looks good therefore sweet alert and the same problem is with modal pop up.
I have never worked in jquery before. This is my first time. I need it for some confirmation dialog. I have write this to test it first before applying in my project. I have written this code. I want dialog box only if specified radio button is selected.
Main Problem: Show Confirmation Dialog if Specified Option in radio button is selected.
Jquery code:
(function($){
$.fn.checkLeave = function() {
return this.each(function(){
if($("input[name='second']").is(':checked')) {
alert("Second Radio Button is CLicked");
$.confirm({
text: "Are you sure to submit the form",
title: "Confirmation required",
confirm: function(button) {
$("form").submit();
},
cancel: function(button) {
// nothing to do
},
confirmButton: "Yes",
cancelButton: "No",
post: true,
confirmButtonClass: "btn-default",
cancelButtonClass: "btn-danger",
dialogClass: "modal-dialog modal-lg"
});
}
});
};
})( jQuery );
and HTML is:
<form action="dialogJquery.html" method="post">
<input type="text" name="username" placeholder="Username">
<input type="radio" id="first">
<input type="radio" name="second" checked="">
<input type="submit" value="Submit" id="submit" name="confirm"
onclick="$(this).checkLeave();"></button>
</form>
The above code shows the alert defined before dialog. but after that dialog is not shown. This is from where i am using Jquery Dialog Plugin. But through debugging when debugger reaches $.confirm and i click on step over then dialog is shown but when i resume script it again disappers.
The basic problem is that the form is being submitted because your code is doing nothing to stop it from being submitted. Accordingly, the dialog is being shown only for the duration of time it takes for the browser to submit the form and go to the specified page (dialogJquery.html).
Once someone who is a better programmer looks at this, they can likely come up with a better solution, but following is what I came up with that seems to work. I have added some IDs to elements and such--you should be able to follow that without further explanation. One thing I found is that if any of the elements has a name or ID of "submit" then the .submit() function will not work on the form.
In general, I handle the submit event for the form and preventDefault so that it doesn't submit. The confirm button sets submitConfirm to true and submits the form.
HTML
<form id="myForm" action="dialogJquery.html" method="post">
<input type="text" name="username" placeholder="Username">
<input type="radio" id="first">
<input type="radio" name="second" checked>
<input type="submit" value="Submit" id="btnSubmit" name="confirm">
</form>
Javascript
(function($) {
var submitConfirm = false;
$("#myForm").submit(function(event) {
if (!submitConfirm) {
event.preventDefault();
if ($("input[name='second']").is(':checked')) {
$.confirm({
text: "Are you sure to submit the form",
title: "Confirmation required",
confirm: function(button) {
submitConfirm = true;
$("#myForm").submit();
},
cancel: function(button) {
// nothing to do
},
confirmButton: "Yes",
cancelButton: "No",
post: true,
confirmButtonClass: "btn-default",
cancelButtonClass: "btn-danger",
dialogClass: "modal-dialog modal-lg"
});
}
}
});
})(jQuery);
I have a popup form but:
- the validation is also a popup and dosnt appear messages
- after submit I would like to get confirmation message in the same popup
<script type="text/javascript">
$(document).ready(function () {
$('#newsletter').click(function (e) {
e.preventDefault();
$('#modal-content').popUpWindow({
action: "open",
modal: true,
size: "large",
buttons: [{
text: "x",
click: function () {
this.close();
}
}]
});
});
});
</script>
<script language="JavaScript" type="text/javascript">
var mailChk =/^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
function checkSubscribe()
{
if($("#snume").val()==''){
$("#msg").html("sdfsdfsfsfsdf");
$("#snume").focus();
return false;
}if($("#semail").val()==''){
$("#msg").html("sdfsdfsfs");
$("#semail").focus();
return false;
} if($("#semail").val()!='' && !mailChk.test($("#semail").val())){
$("#msg").html("sfsdfsfsfd");
$("#semail").focus();
return false;
}
}
</script>
and the form
<div id="modal-content" class="pop-up-display-content">
<h4>Abonare la newsletter</h4>
<p>Acum te poti abona la newsletter folosind formularul de mai jos.</p>
<?
if(isset($_POST['newsll']))
{
skjdklasjdlka
}
?>
<form action="<?=basename($_SERVER['PHP_SELF']);?>" method="post" enctype="multipart/form-data" >
<?=$msg?>
<input type="text" name="snume" class="k8-frm-input" id="snume" placeholder="Nume si prenume"/><br/>
<input type="text" name="semail" class="k8-frm-input" id="semail" placeholder="Email"/><br/>
<input type="submit" name="newsll" value="submit" id="normal" class="btn k8-btn" onclick="return checkSubscribe()"/>
</form>
</div>
After submit, I get message in the form, if I click again the popup button, I see the message from last submit. But I would like to stay open popup and display message.
And after I close the popup, I would like not to see the last message.
And also, I need the validation to display somewhere... The validation is working because I cant submit form, but no messages appears.
Thanks