In the code, the user composes an email by filling out an html form that takes in recipients, subject and body as inputs. I want to display an alert box if the the user didn't provide any recipients. But after clicking OK in the alert box, the inbox.js file re-loads and the user is presented with the "Inbox" mailbox. However, I want them to stay on the compose-mail view instead. I tried to run compose_email function after the alert box but it didn't work. How might I accomplish that?
inbox.js:
document.addEventListener('DOMContentLoaded', function() {
// Use buttons to toggle between views
document.querySelector('#inbox').addEventListener('click', () => load_mailbox('inbox'));
document.querySelector('#sent').addEventListener('click', () => load_mailbox('sent'));
document.querySelector('#archived').addEventListener('click', () => load_mailbox('archive'));
document.querySelector('#compose').addEventListener('click', compose_email);
// By default, load the inbox
load_mailbox('inbox');
});
function compose_email() {
// Show compose view and hide other views
document.querySelector('#display-email').style.display = 'none';
document.querySelector('#emails-view').style.display = 'none';
document.querySelector('#compose-view').style.display = 'block';
// Clear out composition fields
document.querySelector('#compose-recipients').value = '';
document.querySelector('#compose-subject').value = '';
document.querySelector('#compose-body').value = '';
// Send an Email
document.querySelector("#compose-form").onsubmit = function(){
const recipients = document.querySelector("#compose-recipients").value;
const subject = document.querySelector("#compose-subject").value;
const body = document.querySelector("#compose-body").value;
if(recipients.length === 0){
alert(`At least one recipient is required`);
compose_email();
}
else{
fetch('/emails', {
method: 'POST',
body: JSON.stringify({
recipients: recipients,
subject: subject,
body: body
})
})
.then(response => response.json())
.then(result => {
// Print result
console.log(result);
if(result[`error`]){
alert(`User does not exist`)
}
else{
load_mailbox("sent");
}
})
return false;
}
}
}
CodePudding user response:
change your submit function to this and use preventDefault
document.querySelector("#compose-form").onsubmit = function(e){
e.preventDefault();
...
}