Form element wont hide after sending message - javascript

After submitting, I want to hide my form elemnt from page. I've tried using myForm.style.display == "none" but it doesn't work. Can someone assist me?
let myForm = document.getElementById('contact-form');
myForm.addEventListener('submit', (e) => {
e.preventDefault();
const formData = new FormData(myForm);
fetch('#/api/contact_form_messages', {
method: 'post',
body: formData
})
.then((checkStatus))
.then((response) => {
document.getElementById("success-msg").innerHTML = "Success";
myForm.style.display == "none";
return response.text();
})

You need to assign, not compare, this is incorrect:
myForm.style.display == "none"; // Incorrect
This is correct:
myForm.style.display = "none"; // Correct

Related

JavaScript call function after alert box

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;
}
}
}
change your submit function to this and use preventDefault
document.querySelector("#compose-form").onsubmit = function(e){
e.preventDefault();
...
}

How To Display An Error Message When Input Does Not Match Regex?

I simply want to display an error message such as "Email must contain #" and prevent the form from submitting, if there is an error.
How can I go about doing this?
My latest attempt which is a failure:
const email = document.getElementById('email')
const emailmessage = document.getElementById('emailmessage')
const regex = ('^\S+#\S+$')
form.addEventListener('submit', function (event) {
if(!email.value.match(regex)) {
emailchecker();
event.preventDefault();
}
});
let emailchecker = function() {
if(!email.value.match(regex)) {
document.getElementById('emailmessage').innerHTML = '<img src="222.svg" height="15"/> Email Error';
}
Your code is correct, you only need the regex for email validation:
function emailchecker (emailAdress){
let regexEmail = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (emailAdress.match(regexEmail)) {
return true;
} else {
return false;
}
}
let emailAdress = "test#gmail.com";
console.log(emailchecker(emailAdress)); //return true

syntax error only on first load, after refresh page then will be gone

I got this error:
"Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0"
whenever I clear browsing data and refresh page to load my API, but it only shows in the first load, then will be gone after refresh again.
looks it beacuse of cookies or somethings, is there anybody can help me out? Thanks for any help!
JS CODE:
function showDoctorinfo(){
loading();
var url = './api/api.php?action=showDoctorinfo';
fetch(url,
{
method: 'GET',
credentials: 'include',
headers: {
// 'Content-Type': 'application/json',
// 'Accept': 'application/json'
}
},
)
.then(function(response) {
if(response.status === 204) {
closeLoading();
document.getElementById("output-searchDoctorInfo").style.display = 'none';
document.getElementById("allDoctors").style.display = 'none';
console.log('no doctor information')
return;
}
if(response.status === 429) {
closeLoading();
document.getElementById("output-searchDoctorInfo").style.display = 'none';
document.getElementById("allDoctors").style.display = 'none';
console.log('rate limit exceeded')
return;
}
response.json().then(function(data){
closeLoading();
document.getElementById("output-searchDoctorInfo").style.display = 'none';
document.getElementById("allDoctors").style.display = 'none';
document.getElementById("output-doctorinfo").style.display = 'block';
console.log(data);
var source = document.getElementById("doctorinfo-template").innerHTML;
var myTpl = Handlebars.compile(source);
Handlebars.registerHelper("compare",function(v1, v2, options){
if(v1 > v2){
return options.fn(this);
}else{
return options.inverse(this);
}
})
var compiledData = myTpl(data);
document.getElementById("output-doctorinfo").innerHTML = compiledData;
})
})
.catch(function () {
closeLoading();
document.getElementById("alertMessage").style.display = "block";
document.getElementById("alertMessage").innerHTML="Unalbe to connect, please check your internet connection and try again..";
setTimeout(function(){ document.getElementById("alertMessage").style.display="none"}, 4000);
});
}
outStr = showDoctorinfo();
API.PHP CODE:
if(!isset($_SESSION['sessionOBJ'])) {//check session
$_SESSION['sessionOBJ'] = new doctorSession(); //instantiate session to start using
}
at last I found I forget to these two lines in the begining of my php file, private $_startTime; private $_requestCounter; (I used them in my php file for ratelimit)

"if" statement for validating a form doesn't work properly

I have this newsletter form with email input generated with wordpress plugin. Form action is set to a sub-page. I want to check if given email adress is correct - if not, I want to print an alert message.
let emailField = document.querySelector('.email').value;
const regEx = /\S+#\S+\.\S+/;
let submitBtn = document.querySelector('.btn-submit');
let form = document.querySelectorAll('.newsletter-container > form');
function validateEmail() {
if (regEx.test(emailField) == false) {
alert('!!!');
event.preventDefault();
} else {
form.submit();
}
}
submitBtn.addEventListener('click', function (event) {
validateEmail();
});
My problem is, when I type a correct email adress I still get alert and button default event is prevented from action.
What am I doing wrong?
strange construct but anyhow
let submitBtn = document.querySelector('.btn-submit');
function validateEmail() {
var regEx = /\S+#\S+\.\S+/;
let emailField = document.querySelector('.email').value;
if (regEx.test(emailField) == false) {
alert('!!!');
event.preventDefault();
} else {
let form = document.querySelectorAll('.newsletter-container > form');
form.submit();
}
}

How to successfully call the submit when all validations are true

I have created a validation in javascript which detect if there's an empty field and if there's none then it will now insert into database which I use a PHP code.
But it does nothing I'm having trouble inserting into database, I think because I put e.preventDefault(), I put the e.preventDefault() so it will not reload and show the validation messages that I created.
(function() {
document.querySelector('#addForm').onsubmit = function (e) {
e.preventDefault();
const name = document.querySelector('#name');
const age = document.querySelector('#age');
const email = document.querySelector('#email');
//Check empty input fields
if(!document.querySelector('#name').value){
name.classList.add('is-invalid');
}else{
name.classList.remove('is-invalid');
}
if(!document.querySelector('#age').value)
{
age.classList.add('is-invalid');
}else{
age.classList.remove('is-invalid');
}
if(!document.querySelector('#email').value){
email.classList.add('is-invalid');
}else{
email.classList.remove('is-invalid');
}
}
})();
You should only e.preventDefault() if any of the inputs are empty then, example updated:
document.querySelector('#addForm').onsubmit = function(e) {
const name = document.querySelector('#name');
const age = document.querySelector('#age');
const email = document.querySelector('#email');
let formIsInvalid = false;
//Check empty input fields
if (!name.value) {
name.classList.add('is-invalid');
formIsInvalid = true;
} else {
name.classList.remove('is-invalid');
}
if (!age.value) {
age.classList.add('is-invalid');
formIsInvalid = true;
} else {
age.classList.remove('is-invalid');
}
if (!email.value) {
email.classList.add('is-invalid');
formIsInvalid = true;
} else {
email.classList.remove('is-invalid');
}
if (formIsInvalid) {
e.preventDefault();
}
}
You should append AJAX request to send values to the server
var th = $(this);
$.ajax({
type: "POST",
url: "handler.php", //Change
data: th.serialize()
}).done(function() {
alert("Thank you!");
setTimeout(function() {
// Done Functions
th.trigger("reset");
}, 1000);
});

Categories

Resources