e.PreventDefault() not firing as intended, form submission [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
As simple as the title states, why is the e.PreventDefault not executing while all the alerts are?
I only want the page to be forwarded when the alert "All details match" is fired.
My code: https://jsfiddle.net/3fmru8oa/
This is the section I am asking about
<script>
function loginValidator() {
const submitButton = document.getElementById("form");
const username = document.getElementById('uid')
const password = document.getElementById('pwd')
const db = new Localbase("vChatDataBase")
submitButton.addEventListener('submit', function (e) {
console.log(`Inputed field uid: ${username.value}`)
console.log(`Inputed field pwd: ${password.value}`)
db.config.debug = false
db.collection('users').doc({ username: username.value }).get().then(document => {
if(document === undefined) {
alert("No user exist's with this username!")
return e.preventDefault()
} else {
if(document['password'] !== password.value ) {
alert("Incorrect password!")
return e.preventDefault()
} else {
alert("All details matched")
return Cookies.set("cookieUsername", document['username'])
}
}
})
})
}
</script>
I attempted to do this with jQuery yet the same issue remained. I have also tried to return false
Does this have something to do with scoping? And how is this fixed?

Remove the event handler from the loginValidator function. Once you've hooked up an event handler to the submit event, you don't need an onclick method.
In you fiddle code, the problem is when you click submit two things are happening
The loginValidator code is executing, which assigns a event handler to the submit button
The submit event is fired, which redirects you to the profilePage.html page (hence the 404 error)
So what you want to do first is move the code for adding an event handler to the submit event out of the function, so that the event is registered from the start, and not when the button is clicked, because you want that code to run everytime you press submit.
So the script should look something like this
<script>
submitButton.addEventListener('submit', function (e) {
const submitButton = document.getElementById("form");
const username = document.getElementById('uid');
const password = document.getElementById('pwd');
const db = new Localbase("vChatDataBase");
console.log(`Inputed field uid: ${username.value}`)
console.log(`Inputed field pwd: ${password.value}`)
db.config.debug = false
db.collection('users').doc({ username: username.value }).get().then(document => {
if(document === undefined) {
alert("No user exist's with this username!")
return e.preventDefault()
} else {
if(document['password'] !== password.value ) {
alert("Incorrect password!")
return e.preventDefault()
} else {
alert("All details matched")
return Cookies.set("cookieUsername", document['username'])
}
}
})
})
</script>
Just remove the loginValidator function, then see if the issue still happens

Related

How to stop 'submit' form when it is not valid and display error message?

when I put invalid id and password, the page just display the error message and refresh the page. Since I don't want the page to get refresh, how to stop the 'submit'.
const accounts = [
["myaccount", "mypassword1"],
["myaccount2", "mypassword2"],
];
const event = document.getElementById("info");
event.addEventListener("submit", (e) => {
accounts.forEach((element) => {
if (element[0] === id && element[1] === password) {
pass = true;
}
});
if (pass) {
signInForm.action = "builder.html";
} else {
e.stopPropagation();
document.getElementById("error").innerText = "error";
}
});
Try using event.preventDefault() method.
https://www.w3schools.com/jsref/event_preventdefault.asp
else {
e.preventDefault();
e.stopPropagation();
document.getElementById("error").innerText = "error";
}
This might help too - https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation

InboxSDK presending event if condition gets stuck

I am using the presending event of InboxSDK to check for a condition before sending the email. For the case
selectedProject!==0, email is not getting sent. Does anyone have any comments.
composeView.on('presending', (event) => {
if(selectedProject!==0){
//console.log(selectedProject);
composeView.send();
}else{
console.log(selectedProject);
event.cancel();
console.log('please select a project for the email');
alert('please select a project for the email');
initDropdown();//show the dropdown to select projects
}
From the presending handler if you want to send, you need to end the function by returning, if you call composeView.send(); it gets on a cycle calling the presending handler again.
composeView.on('presending', (event) => {
if(selectedProject !== 0){
return;
} else {
...
event.cancel();
...
}
If you want to send later, you need to set a flag that is checked on the presending event to avoid running it again.
composeView.on('presending', (event) => {
if(myForceSendFlag || selectedProject !== 0){
return;
} else {
...
event.cancel();
...
}
I know it's a bit late, but I hope this helps.

Javascript preventDefault() ignored on second submission

I'm experiencing some issues preventing form submission when I try to submit an invalid situation.
Assume I have the following code:
window.onload = function(){
$("form").on("submit",function (event) {
$("#errorDiv").fadeOut(null, null, function () {
OnSubmitForm(event)
});
})
}
function OnSubmitForm(event) {
let items = $("#mytable").dxDataGrid("instance").getSelectedRowsData();
if (items.length == 0) {
event.preventDefault();
} else if (items.some(item => item.booleanProperty != true)) {
event.preventDefault();
let badItems = items.filter(item => item.booleanProperty != true).map(item => item.id);
let divText = "<strong>bad items:<br>"
+ badItems.join("<br>") +"</strong>";
$("#errorDiv").html(divText);
$("#errorDiv").fadeIn();
}
}
My intention is to fadeOut the div I use to display the error, and when the animation is complete I call OnSubmitForm, passing event to it.
The flow of my actions is the following:
I click the submit button
fadeOut kicks in
OnSubmitForm is called
the else if condition is true, so the block is executed
event.preventDefault() works
I click again the submit button
Form is submitted
What's happening?
Plus, I've noted that the result of event.isPreventedByDefault() returns false before the first event.preventDefault(), then it returns true, because the event was already prevented once, according to the MDN documentation.
More info
I forgot to mention that if I do the same violating the first "rule" (first if statement) everything works as expected.
You call OnSubmitForm when the fade out is complete. This happens after the submit event handler function has finished without preventing the default behaviour.
The form has already been submitted by the time you try to stop it.

How could I stop a form submit in this case?

My intention is to check some conditions before submit is done or stop it and show an alert if the results of that condition are false. I need to ask a function localized in another PHP document using POST.
The next case I'm going to show, the alert is showed correctly when "result != 1", but when I test the opposite case "result == 1", the submit doesnt work:
$('body').on("submit","#idForm",function(event) {
event.preventDefault();
$.post( 'php_file_rute.php', {action:'functionName'})
.done(function(result) {
if (result == 1) {
if(functionNameInSameJSPage()){
return true;
}else{
return false;
}
} else {
alert('error');
return false;
}
});
});
I tried in another way, putting event.preventDefault behind every "Return false" but when "result != 1" it shows the alert but do the submit anyways. It happens in every condition (submit doesnt stop).
$('body').on("submit","#formProyecto",function(event) {
$.post( 'php_file_rute.php', {action:'functionName'})
.done(function(result) {
if (result == 1) {
if(functionNameInSameJSPage()){
return true;
}else{
return false;
event.preventDefault();
}
} else {
alert("error");
event.preventDefault();
return false;
}
});
});
As you can see, my goal is to stop the submit if "result != 1" and show an alert or do the submit if all conditions are ok.
Any idea?
Thanks.
The issue you have is that you cannot return anything from an asynchronous function - which your AJAX request is.
To solve this you need to use preventDefault() to stop the form submit event through jQuery, then raise another native submit event if the AJAX request returns a valid result. This second submit event will not be handled by jQuery and will submit the form as you require. Try this:
$(document).on("submit", "#idForm", function(e) {
e.preventDefault();
var form = this;
$.post('php_file_rute.php', {
action: 'functionName'
}).done(function(result) {
if (result === 1) {
if (functionNameInSameJSPage()) {
form.submit();
}
} else {
alert('error');
}
});
});
This is assuming that functionNameInSameJSPage() is not an async function. If it is then you'll need to use the callback pattern there too.
This is a bit of a tricky one but you can kind of get it to work by doing:
$('body').on("submit","#idForm",function(event) {
event.preventDefault();
$.post( 'php_file_rute.php', {action:'functionName'})
.done(function(result) {
if (result == 1) {
if(functionNameInSameJSPage()){
$('#idForm').trigger("submit.force"); //Trigger submit again but under a different name
}
} else {
alert('error');
}
});
});
$('body').on("submit.force","#idForm", function () { return true; }); //Passthrough
The idea is to retrigger the event but ensure you don't call the same handler.
There's a proof of concept at https://jsfiddle.net/2kbmcpa4/ (there's no actual ajax happening but the promise simulates that, note this example won't work in IE)
Steps to solve the issue :
On actual form submit just block the event and make the rest call.
Based on response again dynamically resubmit by setting the allowSubmit flag.
Because flag is set on second submit, it doesn't prevent the form from submission. Reset the allowSubmit flag.
(function() {
var allowSubmit = false;
$('body').on("submit", "#idForm", function(event) {
var that = this;
if (!allowSubmit) {
event.preventDefault();
$.post('php_file_rute.php', {
action: 'functionName'
}).done(function(result) {
if (result == 1) {
if (functionNameInSameJSPage()) {
allowSubmit = true; // set the flag so next submit will not go though this flow
that.submit(); // dynamically trigger submit
}
} else {
alert('error');
}
});
} else {
allowSubmit = false; // reset the flag
}
});
})();

Update to previous validation script (SCHOOL PROJECT)

Well, I have a slight problem in that I read part of the assignment wrong and actually need to have this login any valid email address format and forward it to the 2nd url (myaccount.html). I've tried several things, and while I can get it to login to both the ADMIN page & the MYACCOUNT page, if I put an invalid email in it still logs in (i.e. jdelor1965#yahoo.m). Any ideas?? Thanks...
// Chapters 3 & 4 - login.js (updated during week 3)
// Function called when the form is submitted.
// Function validates the form data and returns a pop-up if conditions are not met.
function validateForm() {
'use strict';
// Get references to the form elements:
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
var pattern = '/^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/';
// Validate!
if (email == 'admin#titanmusicstore.com' && password == 'LogMeIn')
{
window.location = "admin.html";
}
else if (pattern == '/^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/' && pattern == '/^\w+#[a- zA-Z_]+?\.[a-zA-Z]{2,3}$/')
{
window.location = "myaccount.html";
}
else
{
alert('Invalid or incorrect Email or Password!');
}
return false;
}
// End of validateForm() function.
JSFiddle: http://jsfiddle.net/FL2c4/
** I'm wondering if the problem is a conflict between the JavaScript being used and the "form action" in the HTML - either email/passowrd combo will bring me to the page listed in the "form action" field, but when I remove that information the login goes nowhere??
To clarify, this is a school project and not for use in the "real world"! Have received some really good help on here already, so thanks again to those who have assisted. This week, part of our assignment is to change our login validation script to direct the two (2) UID's to different locations. I've read all chapters, watched the videos, and have endlessly researched online but can't figure out how to get this to work - this is what I have, any suggestions or ideas would be greatly appreciated (I can also provide HTML as well - we have a couple pages for that, i.e. index, login, admin, & myaccount).
JavaScript:
// Script Week 2 - login.js
// Function called when the form is submitted.
// Function validates the form data and returns a pop-up if conditions are not met.
function validateForm() {
'use strict';
// Get references to the form elements:
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
var url = window.location.toLowerCase('login.html');
// Validate!
if (email == 'admin#titanmusicstore.com' && password == 'LogMeIn')
{
window.location = "admin.html";
}
else if (email == 'jdelor1965#yahoo.com' && password == 'LogMeIn')
{
window.location = "myaccount.html";
return true;
}
else
{
alert('Please fill out form accurately - Incorrect UID or Password!');
return false;
}
}
// End of validateForm() function.
// Function called when the window has been loaded.
// Function needs to add an event listener to the form.
function init() {
'use strict';
// Confirm that document.getElementById() can be used:
if (document && document.getElementById) {
var loginForm = document.getElementById('loginForm');
loginForm.onsubmit = validateForm;
}
}
// End of init() function.
// Assign an event listener to the window's load event:
window.onload = init;
New code
// Script Week 2 - login.js
// Function called when the form is submitted.
// Function validates the form data and returns a pop-up if conditions are not met.
function validateForm() {
'use strict';
// Get references to the form elements:
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
// var url = window.location.toLowerCase('login.html'); DELETE -- does nothing
// Validate!
if (email == 'admin#titanmusicstore.com' && password == 'LogMeIn') {
window.location = "http://talk.collegeconfidential.com/";
} else if (email == 'jdelor1965#yahoo.com' && password == 'LogMeIn') {
window.location = "http://disney.com";
} else {
alert('Please fill out form accurately - Incorrect UID or Password!');
}
return false;
}
// End of validateForm() function.
// Function called when the window has been loaded.
// Function needs to add an event listener to the form.
function init() {
'use strict';
// Confirm that document.getElementById() can be used:
if (document && document.getElementById) {
var loginForm = document.getElementById('loginForm');
loginForm.onsubmit = validateForm;
}
}
// End of init() function.
// Assign an event listener to the window's load event:
window.onload = init;
You need to return false from the validateForm function false every time to stop the form from submitting on its own. Since it's false under every condition, I moved that statement to the end of the function.
I changed the URLs so they would work in FIDDLE.
I also changed your fiddle from onLoad to No wrap so your own onload handler would work.
change your fiddle to HEAD instead of onload
You need to remove all return statements and have ONE return false in the validate like this http://jsfiddle.net/mplungjan/mt8Vb/
Like this
window.onload = function () { // when the page has loaded
// find the form and attach an event handler to the submit
document.getElementById('loginForm').onsubmit = function () {
// Get references to the form elements:
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
// Validate!
if (email == 'xxx...musicstore.com' && password == 'LogMeIn') {
window.location = "admin.html";
} else if (email == 'yyy...yahoo.com' && password == 'LogMeIn') {
window.location = "myaccount.html";
} else {
alert('Please fill out form accurately - Incorrect UID or Password!');
}
return false; // you never want to actually submit the form
}
}

Categories