Add a confirmation alert before submitting a form - forms

I have a form which allows the user to delete some data from a database.
I want to have a bit of confirmation to prevent accidental deletes. I want to do the following:
When submit is pressed, alert pops up with "Are you sure?"
If user hits "yes" then run the script
If user hits "no" then don't submit the script.
How can this be done?
I have added the onSubmit alert but it does not show anything, and it still submits the form. How can I delay the submission of the form to only occur when the user selects "yes" from the alert?
<form
method="POST"
action="actions/remove-daily-recipient.php"
onSubmit="alert('Are you sure you wish to delete?');"
>
...
</form>

Instead of alert, you have to use confirm and return in your form, for an example:
<form
method="post"
onSubmit="return confirm('Are you sure you wish to delete?');">
...
</form>

on your form can you try with a js function like:
<form onsubmit="return submitResult();">
and on your function have something like?
function submitResult() {
if ( confirm("Are you sure you wish to delete?") == false ) {
return false ;
} else {
return true ;
}
}
I think this will be a good start.

Stop the default behaviour, ask for confirmation and then submit the form:
var form1 = document.getElementById('form1');
form1.onsubmit = function(e){
var form = this;
e.preventDefault();
if(confirm("Are you sure you wish to delete?"))
form.submit();
}
JS Fiddle: http://jsfiddle.net/dq50e963/

Related

Prevent closing browser tab when form is dirty in Angular 2

How to prevent closing browser tab when form is dirty in Angular 2?
My html body contains a component:
<body>
<my-app>Loading, please wait...</my-app>
</body>
which contains a router navigation and a router outlet:
<nav>
(...)
</nav>
<router-outlet></router-outlet>
and when the router navigates to the edit page, I have some form there:
<form #myForm="ngForm">
<button pButton type="text" label="Save" (click)="onSave()" [disabled]="!myForm.valid || myForm.pristine"></button>
</form>
Now, if the form is not 'pristine', I want to ask for confirmation when the user tries to close the browser tab:
window.onbeforeunload = function() {
if (form.dirty) {
return "You have unsaved data changes. Are you sure to close the page?"
}
}
How can I access the dirty state of Angular form in canonical way from there? I could register an event to field change on each field and set the global dirty flag, but I'd have to put that code on every from and by every navigation and then maintain that code so that the message stays consistent. Is there any other way to check out if there's an angular form on the page, which is in dirty state?
Perhaps
#HostListener('window:beforeunload', ['$event'])
handleBeforeUnload(event) {
if (connected) {
return "You have unsaved data changes. Are you sure to close the page?"
}
}
Add a Hostlistener decorator. If there are unsaved changes on the form confirm dialog appears.
#HostListener('window:beforeunload', ['$event'])
handleBeforeUnload(event: Event) {
event.returnValue = false;
}
This works. Implement the hasUnsavedData() function accordingly.
hasUnsavedData(){
return this.myForm.dirty;
}
#HostListener('window:beforeunload', ['$event'])
handleBeforeUnload($event: any) {
if (this.hasUnsavedData()) {
$event.returnValue = true;
}
}
Simply you can use Jquery to get state of ng-form.
#HostListener('window:beforeunload', ['$event'])
beforeUnloadHandler(event) {
if($('form').hasClass('ng-touched')) { //You can check with ng-dirty based on your requirements.
let confirmMessage = 'You have unsaved data changes. Are you sure to close the page?'
event.returnValue = confirmMessage;
return confirmMessage;
}
}
In my case am just showing warning dialog if that the form has been touched.
Try this directive https://github.com/extremeprog-com/ng-prevent-navigation.
So it should be simple
<div ng-prevent-navigation="vm.pageShouldBeReloaded"
ng-prevent-navigation-text="Payment form has unsaved changes.
If you leave the page now you will lose those changes."
></div>

mixpanel track form submission with validation

I have a form which I want to use mixpanel to track some properties when I submit. How can I stop the form submit through mixpanel if the validation return false ?
Here's my code in general.
My simple form
<form id="form" action="..." method="post" role="form">
// my elements here
<input type="submit" value="Submit" />
</form>
My script
<script>
function(){
mixpanel.track_forms("form", "MyEventName", getProperties());
$("form").submit(SubmitForm);
function getProperties(){
// get properties here
}
function SubmitForm() {
if (SomethingNotRight()) { return false; }
return true;
}
}
My problem:
I expect that in my SubmitForm function, after validation by SomethingNotRight function, it will stop the submit. However, even when SubmitForm returns false, the form keep submitting to the server, which I found out is because of the mixpanel.track_form.
The reason I use mixpanel.track_form is to avoid the race condition between form submit and mixpanel submit as debugging mixpanel track form
I can definitely understand the issue here, and the reason is that track_forms is just designed for the default use case of a form submitting right away. If you have a process in between (in this case a validation), you should basically do your own implementation. The idea of track_forms is to identify the form being submitted, log the event, wait for a while so that the event can be saved, and then proceed. In that sense, you can do:
(function(){})(
var theForm = $("#form"),
readyToProceed = false;
//listen for the submition
theForm.submit(function(e){
if(!readyToProceed){
e.preventDefault();
processSubmit();
}
});
function processSubmit(){
//validation process
if (SomethingNotRight()) { return false; }
//we are all good, lets proceed
mixpanel.track("Form submitted");
readyToProceed = true;
window.setTimeout(function(){ theForm.submit() }, 300);
}
);

Google Apps Script HTMLService display confirmation page after form submit

I created a web app form using Google Apps Script and the HTMLService.
It is a one-page form with a submit button at the bottom.
When submitted, the form validates whether the data input into the form is valid, and if valid, it logs the form data to a spreadsheet.
That all works so far.
I now need the user to be sent to a confirmation page, and the confirmation page needs to be able to have parameters passed to it (to display certain information on the confirmation page).
main.gs:
function doGet(e) {
var template = HtmlService.createTemplateFromFile('form');
return template.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function processFormSubmission(formData) {
Logger.log('starting processPoRequest');
Logger.log('po: ' + JSON.stringify(formData, null, 2));
// code for appending data to sheet here
}
form.html:
<!DOCTYPE html>
<form id="form1" name="form1">
<label for="info" id="info_label">Info</label>
<input id="info" name="info" type="text">
<input class="btn" id="button" onclick="onClickFunctions(document.getElementById('form1'))" type="submit" value="Submit">
</form>
<script>
function onClickFunctions(formData) {
console.log('starting onClickFunctions');
var allDataValid = validateForm(formData);
if (allDataValid === true) {
google.script.run.withSuccessHandler().processFormSubmission(formData);
}
}
function validateForm(form) {
console.log('starting validateForm');
var errors = 0;
var element = document.getElementById('info');
if (!form.info) { element.classList.add("validation_error"); errors++; if (errors === 1) element.focus(); }
else element.classList.remove("validation_error");
if (errors > 0) return false;
else return true;
}
</script>
confirmation.html:
<!DOCTYPE html>
<?!= confirmationMessage ?>
I don't know what to put in .withSuccessHandler() to make it so that the user is brought to the confirmation page.
I've Googled this extensively and found these results on Stack Overflow, and each one suggests a different solution, but none of them actually include complete working code for a solution:
Possible solutions using doPost:
Send form by email and track responses in spreadsheet
HtmlService doPost With Google Docs Form
HtmlService doPost
I messed around with doPost but I couldn't figure out how to get it to be invoked, and I couldn't find any official documentation in the HTMLService docs.
Possible solution using the link to the web app in an a href:
href in HtmlService
If my button was a link that looked like a button, I'm not sure how I would execute the form validation function when the link is clicked.
I have done this two different ways.
had a hidden statement that gets shown, and the form gets hidden.
or
use .withSuccessHandler(google.script.host.close()), but have the processFormSubmission function open a new dialogue.

jQuery Stop .blur() event when clicking "submit" button

I am building a small landing page with a simple demo e-mail signup form. I want to have the form field open up when focused, and then shrink back down on blur.
However the problem I'm facing is when you click the submit button this instigates the blur function, hiding the button and shrinking the form. I need to find a way to stop the .blur() method only when the user is clicking to focus on the submit button. Is there any good workaround for this?
Would appreciate any help I can get!
I know this question is old but the simplest way to do it would be to check event.relatedTarget. The first part of the if statement is to prevent throwing an error if relatedTarget is null (the IF will short circuit because null is equivalent to false and the browser knows that it doesn't have to check the second condition if the first condition is false in an && statement).
So:
if(event.relatedTarget && event.relatedTarget.type!="submit"){
//do your animation
}
It isn't the prettiest solution, but it does work. Try this:
$("#submitbtn").mousedown(function() {
mousedownHappened = true;
});
$("#email").blur(function() {
if (mousedownHappened) // cancel the blur event
{
mousedownHappened = false;
}
else // blur event is okay
{
$("#email").animate({
opacity: 0.75,
width: '-=240px'
}, 500, function() {
});
// hide submit button
$("#submitbtn").fadeOut(400);
}
});​
DEMO HERE
Try this inside .blur handler:
if ($(':focus').is('#submitbtn')) { return false; }
why not rely on submit event instead of click? http://jsbin.com/ehujup/5/edit
just couple changes into the html and js
wrap inputs into the form and add required for email as it obviously suppose to be
<form id="form">
<div id="signup">
<input type="email" name="email" id="email" placeholder="me#email.com" tabindex="1" required="required">
<input type="submit" name="submit" id="submitbtn" value="Signup" class="submit-btn" tabindex="2">
</div>
</form>
in js, remove handler which listen #submitbtn
$("#submitbtn").on("click", function(e){
e.stopImmediatePropagation();
$("#signup").fadeOut(220);
});
and use instead submit form listerer
$("#form").on("submit", function(e){
$("#signup").fadeOut(220);
return false;
});
you may use $.ajax() to make it even better.
Doing this you gain point in terms of validation and the native browser's HTML5 validator will make check email format where it is supported.

jquery / ajax form not passing button data

I thought the HTML spec stated that buttons click in a form pass their value, and button "not clicked" did not get passed. Like check boxes... I always check for the button value and sometimes I'll do different processing depending on which button was used to submit..
I have started using AJAX (specifically jquery) to submit my form data - but the button data is NEVER passed - is there something I'm missing? is there soemthing I can do to pass that data?
simple code might look like this
<form id="frmPost" method="post" action="page.php" class="bbForm" >
<input type="text" name="heading" id="heading" />
<input type="submit" name="btnA" value="Process It!" />
<input type="submit" name="btnB" value="Re-rout it somewhere Else!" />
</form>
<script>
$( function() { //once the doc has loaded
//handle the forms
$( '.bbForm' ).live( 'submit', function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $( this ).serialize(), // get the form data
type: $( this ).attr( 'method' ), // GET or POST
url: $( this ).attr( 'action' ), // the file to call
success: function( response ) { // on success..
$('#ui-tabs-1').html( response );
}
});
return false; // cancel original event to prevent form submitting
});
});
</script>
On the processing page - ONLY the "heading" field appears, neither the btnA or btnB regardless of whichever is clicked...
if it can't be 'fixed' can someone explain why the Ajax call doesn't follow "standard" form behavior?
thx
I found this to be an interesting issue so I figured I would do a bit of digging into the jquery source code and api documentation.
My findings:
Your issue has nothing to do with an ajax call and everything to do with the $.serialize() function. It simply is not coded to return <input type="submit"> or even <button type="submit"> I tried both. There is a regex expression that is run against the set of elements in the form to be serialized and it arbitrarily excludes the submit button unfortunately.
jQuery source code (I modified for debugging purposes but everything is still semantically intact):
serialize: function() {
var data = jQuery.param( this.serializeArray() );
return data;
},
serializeArray: function() {
var elementMap = this.map(function(){
return this.elements ? jQuery.makeArray( this.elements ) : this;
});
var filtered = elementMap.filter(function(){
var regexTest1= rselectTextarea.test( this.nodeName );
var regexTest2 = rinput.test( this.type ); //input submit will fail here thus never serialized as part of the form
var output = this.name && !this.disabled &&
( this.checked || regexTest2|| regexTest2);
return output;
});
var output = filtered.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val, i ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
return output;
}
Now examining the jQuery documentation, you meet all the requirements for it to behave as expected (http://api.jquery.com/serialize/):
Note: Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button. For a form element's value to be included in the serialized string, the element must have a name attribute. Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked. Data from file select elements is not serialized.
the "successful controls link branches out to the W3 spec and you definitely nailed the expected behavior on the spec.
Short lame answer: I think it is teh broken! Report for bug fix!!!
I've run into a rather unusual issue with this. I'm working on a project and have two separate php pages where one has html on the page separate from the php code and one is echoing html from inside php code. When I use the .serialize on the one that has the separate html code it works correctly. It sends my submit button value in its ajax call to another php page. But in the one with the html echoed from the php script I try to do the same thing and get completely different results. It will send all of the other info in the form but not the value of the submit button. All I need it to do is send whether or not I pushed "Delete" or "Update". I'm not asking for help (violating the rules of asking for help on another persons post) but I thought this info might be helpful in figuring out where the break down is occurring. I'll be looking for a solution and will post back here if I figure anything out.