HTML Form and Javascript Confirmation - javascript

I'm having a problem with submitting a form and Javascript confirmation. Basically, the following Javascript is called when the "submit" button is pressed.
function confirmation() {
var answer = confirm("Are you sure you wish to edit?")
if (answer)
{
window.location = "#editform2";
}
}
However, when I hit the cancel instead of ok, the Javascript executes correctly, because I watch the address bar and it doesn't update to #editform2. The form, however, still submits. It seems to refresh the page. Here's the relevant parts from the form:
//Form is encoded in PHP
<form method=\"post\">
//Form is in here
<input type=\"submit\" value=\"Edit\" onclick=\"confirmation()\">
So the form doesn't know where it's going, it just refreshes the page, and the page happens to be the processor as well. So it's processing even though I clicked cancel and the Javascript should keep it on the same page. Besides moving the processing to a different page, what are my solutions?

It works like this because it's a sumbit button and the form is submitted in every case. Assign an id to the form and change the input type:
<form method="post" id="formid">
<input type="button" value="Edit" onclick="confirmation()">
and call this function on click:
function confirmation() {
var answer = confirm("Are you sure you wish to edit?")
if (answer)
{
document.getElementById("formid").submit();
}
}

Don't use the onclick event of the submit button, use the onsubmit event of your form:
document.forms[0].onsubmit = function () {
return confirm("Are you sure you wish to edit?");
}
You may want to add a id attribute to your form to identify it.
Keeping event binding on JavaScript code; not on inline attributes on your HTML, makes your code more maintanable and easy to debug.

try:
return answer;
at the end of the function and make sure the onclick method returns this. Like so:
<input type="submit" value="Edit" onclick="return confirmation()">
This would make the function return false and have the form not be posted.

Related

JS removes form data before PHP can send email

Ran into a small oddity here.
When I submit a form, I have a JS click event listener on the submit button - this is to remove the HTML values and add a thank you message (pretty simple stuff).
Oddly, however, it seems that the JS is acting before the PHP because all emails have blank values until I remove the JS that removes the HTML values.
The code is:
pretty simple HTML form (this has been cut down to show what the problem might be)
HTML:
<form method="post" action="contactForm.php" id="contact-form" target="hiddenForm">
<textarea class="form-control input-outline reqItem" rows="6" cols="50" name="message" form="contact-form" placeholder="Message" required></textarea>
<button type="submit" class="btn btn-outline rounded-0 d-block d-md-inline-block submit-button">Submit</button>
</form>
JS (has an event listener on the submit button for click):
if(document.querySelector('.submit-button')){
document.getElementById('contact-form').addEventListener('submit', function(e){
// Check that form is valid
if(document.querySelector('form').checkValidity()){
document.querySelectorAll('.checkbox').forEach(e => {
if(e.classList.contains('checked')){
e.classList.remove('checked')
}
})
// Change messagae to thank you
e.target.classList.add('submit-hide')
document.querySelector('.submit-thankyou').classList.add('submit-show')
// remove all field values <<<<< issue seems to be being caused here
document.querySelectorAll('.form-control').forEach(e => {
// this causes the form to lose all data
e.disabled = true;
})
}
})
}
The e.disabled = true;
Is going over each form input and making it disabled, I have also used e.value = "".
Both of these stop PHP action in the form of setting variables as the values of the inputs.
So the question is,
am I doing something wrong (maybe right.....?)
is there a way to allow the PHP to act first getting the values before removing them with the JS?
Feel free to ask any questions here.
Any insights are welcome.
The submit event as part of the browser's form submission algorithm, before the browser even looks at the form's fields, so any changes you make as part of that event will be submitted to the server and you'll have access to them from PHP.
In order to change the form without affecting the submission, you'll have to do that at some point after the browser's form submission finishes, but before the page navigates to the form's action:
document.getElementById('contact-form').addEventListener('submit', function(){
setTimeout(function() {
// Modify the form here.
}, 0);
});
Remember that setTimeout(func, msecs) means "run func whenever you have the chance, but no earlier than msec milliseconds". While the browser is running the form submission algorithm, no Javascript code (other than that for the synchronous events submit and formdata) can run, so the earliest chance for func to run will be after the form is submitted.

PureCSS stop page reload on form submit but retain form validation

I'm trying to use PureCSS forms in my web app and I can't figure out how to retain the nifty form validation while stopping the page reload.
I know I can stop the page reload using onsubmit="return false;"
Then I can use AJAX to post the form data using onClick="PostSettings();", where PostSettings() is my javascript function containing the AJAX request. I also have to include event.preventDefault(); at the top of that function to stop the reload.
Unfortunately these steps which stop the reload also stop the nice in-built PureCSS validation.
Is there a way to retain that without triggering the page reload or will I need to make my own validation in the javascript?
FYI, here's the html:
<button type="submit" class="pure-button pure-input-1-2 pure-button-primary"
id="save-simulation-button" onClick="PostSettings();"
onsubmit="return false;">
<i class="fa fa-save"></i> Submit Simulation Parameters
</button>
Use 'return false' instead of event.preventDefault() inside the 'PostSettings()' method.
Thanks for your replies Lucas and Vignesh -- they didn't quite solve the problem, but they got me thinking and I developed a solution:
In the html I had to add a return here: onClick="return PostSettings();"
Then in the javascript I return true or false depending on whether or not the form passes validation, which I have to check:
function PostSettings() {
//event.preventDefault(); <<- commented out per Vigneshs suggestion
var name = $("#simulation-name").val(); // jquery to get form values
var description = $("#description").val();
// Code to validate form: name and description cannot be blank
if (name === "" || description === "") {
console.log("name or description fields cannot be blank");
return true; // <<- returning true allows PureCSS validation to continue
}
// Code passed validation so post the data...
// POST code omitted for brevity
return false; // <<- returning false stops the page reload
}
So in summary, returning true allows the PureCSS form validation to take place as per normal (and there's no page reload because the form hasn't passed validation). And when the form passes validation I return false to stop the page reload -- this also stops any other default events of the PureCSS form, but that's okay because I manually checked if it validated in the javascript.
Hope this helps others who want to accomplish this in the future!
You only need a onsubmit="return MyValidFunction();" in the Form tag and nothing else in the "submit" button
When the form is not ok PureCSS make the validation with his message, When All is ok call your "MyValidFunction()" function
function MyFunction() {
/// your Ajax Code here
return false;
}
<form class="pure-form" onsubmit="return PostSettings();">
<input id="form_url" type="url" class="pure-input-1-3">
<button type="submit" class="pure-button pure-input-1-1">OK</button>
</form>
I had the same issue. Adding onsubmit="event.stopPropagation()" in the form tag prevents the refresh when the form is valid, and retains validation flags when it's invalid.

Reading form value fails - Javascript

I`m trying to read the value from an input and fill it in one empty div.However , the value is being read but when I click the button submit , the value appears for like 0.2 seconds on the empty div , and then , disappears ... any suggestions why?
HTML :
<div id="vuvedenaSuma">
</div>
<form action="">
<input type="text" id="suma" required="required" placeholder="Въведи сума" name="Suma" />
<button id="submit">Submit!</button>
</form>
Javascript:
function valueRead(){
var vuvedenaSuma = document.getElementById('suma').value;
document.getElementById('vuvedenaSuma').innerHTML = vuvedenaSuma;
}
document.getElementById('submit').addEventListener('click',valueRead);
I want to make it withe eventListener , not onclick attribute on the button.
Your form is being submitted right after the execution of the function.
You can prevent the default event(form submission) to be called with event.preventDefault() like this:
function valueRead(e){
var vuvedenaSuma = document.getElementById('suma').value;
document.getElementById('vuvedenaSuma').innerHTML = vuvedenaSuma;
e.preventDefault();
}
https://jsfiddle.net/ez0qchyq/
Your event is firing, then the page is likely reloading because of the form firing. Try using
event.preventDefault()
and it will prevent the form from submitting.
Edit: Also, the comment below me is absolutely correct. Remember to pass the event into the function.
The default way that a form "submits" is to send a new page request to the server, using the given inputs as parameters. From there, a serverside language like PHP might save them. Often, this would churn out an "Operation successful!" page or similar.
In your case, your form's action is blank, meaning it will "submit" to the page it's on. Since your page is pretty basic, it will reload without any of the sent information appearing in it.
As John Kossa suggested, you could intercept this by adding an argument, let's say, "evt", to the parentheses of the valueRead function, and then calling evt.preventDefault().
When you click the button then you send the form and the page is automatically refreshed. To prevent this behavior try this solution
function valueRead(e){
e.preventDefault();
var vuvedenaSuma = document.getElementById('suma').value;
document.getElementById('vuvedenaSuma').innerHTML = vuvedenaSuma;
}
Also, you might want to use the event listener on submit:
document.getElementById('formName').addEventListener('submit', valueRead);

How to stop user from leaving page after submitting form (i.e. while it's processing)?

There are lots of similar questions on here, but I haven't found any that deal with stopping a user from leaving a page after submitting a form (i.e. while it's processing).
I have a page on my website with a form that takes a long time to submit (sometimes as long as 15 seconds), so I want to have a popup warning to keep the user on the page after they submit the form.
The problem is that no matter how I try using window.onbeforeunload, I always get a confirmation dialog from that function when the form is submitted, which is not what I want. I don't want the user to get the confirmation dialog when the form is submitted, but rather after it's submitted and only if they try to leave the page after that.
HTML:
<form id="myform" method="post" action="" onsubmit="formSubmitted();">
<button type="submit" onclick="return checkForm();">submit form</button>
</form>
Javascript:
formSubmittedFlag = 0;
function checkForm()
{
...
if(...)
{
return true;
}
else
{
return false;
}
}
function formSubmitted()
{
formSubmittedFlag = 1;
}
window.onbeforeunload = function()
{
if(formSubmittedFlag == 1)
{
return "Are you sure you want to leave the page?";
}
}
Is there a way to accomplish what I'm wanting?
Submit the form using AJAX rather than the form's built-in action. The jQuery Form Plugin may be helpful.
replace the contents of formSubmitted with this:
sessionStorage.formSubmittedFlag=true;
notReloaded=true;
And replace the contents of window.onbeforeunload with this:
if(sessionStorage.formSubmittedFlag===true&&notReloaded!=true)
return 'do you want to leave?';

How to post form using jQuery?

I have a form with a submit button and it works fine, but I now have a user request to make the form get saved (posted to save action) if a link on the page is clicked and the form is "dirty".
I've got the logic in place by having an isDirty JavaScript variable, now I would like to post the form from the JavaScript function when it is dirty.
My form declaration is as follows:
<form id="formSmart" action="<%= ResolveUrl("~/SmartForm/Proceed") %>"
method="post" enctype="multipart/form-data">
and my JavaScript is:
function checkLink() {
if (isDirty) {
$("#formSmart").submit();
}
}
The proceed action doesn't get called, yet when I click the submit button on the form it works fine. What am I doing wrong in the JavaScript?
Note: The call to checkLink() works fine, the ultimate problem is that $("#formSmart").submit(); is not posting to the Proceed action.
You have the correct way of submitting the form based on what you have posted and the names match up.
Are you sure you are calling checkLink and is isDirty equal to true?
Put and alert('Test'); right before you submit and in the if scope.
EDIT: To hookup your event you need to do the following:
$('#yourLinkID').click(checkLink(); return false;);
Note the return false which will cause your link to not execute a navigate. If you want the link to navigate, you can just remove that part.
Sounds like the requirement is that 'a link on the page is clicked'.
Perhaps attach this event to all the <a> tags on the page.
$(document).ready(function() {
// all <a> tags get the checkLink attached to them
$("a").click(checkLink());
});
your problem is that the browser navigate before the page performs your submit.
the solution is suspending the navigation till you save the form.
The UGLY solution:
you could do it buy saving the clicked url at a hidden field,
returning false to stop the navigation,
and after submit check for a value there and if it exists do navigation
A better solution:
post the form via ajax and after the ajax call completes(no need to check for success or error) perform the navigation(to make it really easy just use ajaxForm ajaxForm plugin)
the only problem with this solution is if the link has target="_blank" because then you have to use window.open which might be blocked by popup blockers
you can play with a simple jsbin sample i prepared showing this
this example post some values to an older version of this page + navigate to google, open fiddler and see that it first post and then navigate.
If you went to the jsbin page stop reading here
here is the Html:
<form id="formSmart" action="http://jsbin.com/oletu4/edit" method="post">
<input type="text" name="someLie" />
<input type="text" name="someLie2" />
<input type="submit" value="submit" />
<a id="lnkNavOut" href="http://www.google.com">www.google.com</a>
here is the JS:
$(document).ready(function(){
$("#lnkNavOut").click(function(){
var jqFormSmart = $("#formSmart");
//check here if the form is dirty and needs to be saved
var jqClickedLink = $(this);
$.ajax({
url: jqFormSmart.attr("action"),
type: "POST",
data:jqFormSmart.serialize(),
complete:function(){
location = jqClickedLink.attr("href");
}
});
return false;//stop navigation
});
});​

Categories