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.
Related
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
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
}
});
})();
This question has been done to death on SO and I'm really, really sorry! I've already taken the bones of the below idea from a couple of SO questions on the same theme.
All said though, I still can't get it to work as expected.
It works OK if NONE are filled in.
It works OK if the END input is filled in and not the others.
It works OK if the MIDDLE input is filled in.
If you fill in ONLY the FIRST input though, it alerts, but submits anyway?
JSFIDDLE
$(document).ready(function (e) {
// completed count submit handler
$("#submit_counts_button").on('click', function () {
window.incomplete = false;
$('input[type=number]').each(function () {
if ($(this).val().length == 0) {
window.incomplete = true;
alert('Some fields are empty');
return false;
} else {
if (window.incomplete === false) {
$("#submit_counts_button").prop('disabled', true);
$("#submit_counts_button").html('Please Wait ...');
//$("#update_form").submit();
}
}
});
});
});
I'm sure it's something totally embarrassingly obvious but after a 16 hour day, I just can't see it. Any help appreciated ...
You need to pull the 'incompletion' check outside of the .each
$(document).ready(function (e) {
// completed count submit handler
$("#submit_counts_button").on('click', function () {
window.incomplete = false;
$('input[type=number]').each(function () {
if ($(this).val().length == 0) {
window.incomplete = true;
alert('Some fields are empty');
return false;
}
});
if (window.incomplete === false) {
$("#submit_counts_button").prop('disabled', true);
$("#submit_counts_button").html('Please Wait ...');
//$("#update_form").submit();
}
});
});
http://jsfiddle.net/6WpeF/6/
try
if(document.getElementById('id of input').value != ""){}
Trying to cancel the sending of an empty form. Confused as there seems to be no reason why this doesnt work. Using firefox as my browser.
Could anybody explain why this code does not cancel the form being sent yet it fires the alert dialog.
addEvent(searchForm, "onsubmit", function(){
if(inputBox.value.trim() === ""){
alert("empty"); //this line gets called
return false; //this doesn't
}
});
Many Thanks
this is the addEvent function
function addEvent(element, listener, func){
if(element.addEventListener){
listener = listener.substr(2, listener.length);
element.addEventListener(listener, func);
} else {
element.attachListener(listener, func);
}
}
your handler should be
function(e){
if(inputBox.value.trim() == ""){
alert('empty');
e.preventDefault();
}
}
Normally regardless of the framework used handlers support passing the event itself as an argument.
addEvent is not a native javascript function.
use this instead..
searchForm.onsubmit = function(e){
if(inputBox.value.trim() === ""){
alert("empty");
e.preventDefault();
return false;
}
}
I have a form, and when I submit him I execute multiple script. Here is my code:
$("#RequestCreateForm").submit(function (e) {
if ($("#RequestCreateForm").validate().checkForm() == false) { return; }
e.preventDefault();
//many scripts
//How to continue submitting?
}
Is it possible to continue submitting the form (which is stopped with e.preventDefault();) after //many scripts?
Thank you
When you call $("#RequestCreateForm").submit(), the script will just run through the event handler again, and cause an infinite loop (as Koen pointed out in a comment on the accepted answer). So, you need to remove the event handler before submitting:
$("#RequestCreateForm").on('submit', function (e) {
e.preventDefault();
// do some stuff, and if it's okay:
$(this).off('submit').submit();
});
The last line needs to be in a conditional statement, otherwise it'll just always happen, and negate your e.preventDefault(); at the top.
$("#RequestCreateForm").submit(function (e) {
if ($("#RequestCreateForm").validate().checkForm() === false) {
e.preventDefault();
//form was NOT ok - optionally add some error script in here
return false; //for old browsers
} else{
//form was OK - you can add some pre-send script in here
}
//$(this).submit();
//you don't have to submit manually if you didn't prevent the default event before
}
$("#RequestCreateForm").submit(function (e) {
if ($("#RequestCreateForm").validate().checkForm() == false)
{
e.preventDefault();
return false;
}
//other scripts
}
All solutions here are too complicated or lead to javascript error, simpliest and clearest solution I guess:
jQuery("#formid").submit(function(e) {
if( ! (/*check form*/) ){ //notice the "!"
e.preventDefault();
//a bit of your code
} //else do nothing, form will submit
});
$("#RequestCreateForm").submit(function (e) {
if ($("#RequestCreateForm").validate().checkForm() == false) { return; }
e.preventDefault();
//many scripts
// Bypass the jquery form object submit and use the more basic vanilla
// javascript form object submit
$("#RequestCreateForm")[0].submit();
}
To avoid submit loops, an additional variable should be used.
var codeExecuted = false;
$('#RequestCreateForm').submit(function(e) {
...
if(!codeExecuted){
e.preventDefault();
...
functionExecuted = true;
$(this).trigger('submit');
}
});
Here is my approach to avoid the infinite loop.
In the form, I use a "button" with an id (e.g. <input type="button" id="submit" value="submit"/>) to mimic the submit button;
In the script I have something like this:
$('#submit').click(function() {
if(//validation rules is ok)
{
$("#RequestCreateForm").submit(); //assuming the form id is #RequestCreateForm
}
else
{
return false;
}
});
return; is the same thing as e.preventDefault();
try
$("#RequestCreateForm").trigger('submit');