This is a simple contact form using HTML CSS and JavaScript. I am not able to get a message after the form submit button is entered. It redirects me to a page that displays the submitted details and I don't want that to happen obviously. I wish to get a toast message after submit button is clicked, and to reset the form. I have added an extra button just to check functionality for toast. I am really stuck on this!!
Please help!
form demo
(function() {
// get all data in form and return object
function getFormData(form) {
var elements = form.elements;
var honeypot;
var fields = Object.keys(elements).filter(function(k) {
if (elements[k].name === "honeypot") {
honeypot = elements[k].value;
return false;
}
return true;
}).map(function(k) {
if (elements[k].name !== undefined) {
return elements[k].name;
// special case for Edge's html collection
} else if (elements[k].length > 0) {
return elements[k].item(0).name;
}
}).filter(function(item, pos, self) {
return self.indexOf(item) == pos && item;
});
var formData = {};
fields.forEach(function(name) {
var element = elements[name];
// singular form elements just have one value
formData[name] = element.value;
// when our element has multiple items, get their values
if (element.length) {
var data = [];
for (var i = 0; i < element.length; i++) {
var item = element.item(i);
if (item.checked || item.selected) {
data.push(item.value);
}
}
formData[name] = data.join(', ');
}
});
// add form-specific values into the data
formData.formDataNameOrder = JSON.stringify(fields);
formData.formGoogleSheetName = form.dataset.sheet || "responses"; // default sheet name
formData.formGoogleSendEmail = form.dataset.email || ""; // no email by default
return {
data: formData,
honeypot: honeypot
};
}
function handleFormSubmit(event) { // handles form submit without any jquery
event.preventDefault(); // we are submitting via xhr below
var form = event.target;
var formData = getFormData(form);
var data = formData.data;
// If a honeypot field is filled, assume it was done so by a spam bot.
if (formData.honeypot) {
return false;
}
disableAllButtons(form);
var url = form.action;
var xhr = new XMLHttpRequest();
xhr.open('POST', url);
// xhr.withCredentials = true;
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
form.reset();
var formElements = form.querySelector(".form-elements")
if (formElements) {
formElements.style.display = "none"; // hide form
}
var thankYouMessage = form.querySelector(".thankyou_message");
if (thankYouMessage) {
thankYouMessage.style.display = "block";
}
}
};
// url encode form data for sending as post data
var encoded = Object.keys(data).map(function(k) {
return encodeURIComponent(k) + "=" + encodeURIComponent(data[k]);
}).join('&');
xhr.send(encoded);
}
function loaded() {
// bind to the submit event of our form
var forms = document.querySelectorAll("form.gform");
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener("submit", handleFormSubmit, false);
}
};
document.addEventListener("DOMContentLoaded", loaded, false);
function disableAllButtons(form) {
var buttons = form.querySelectorAll("button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].disabled = true;
}
}
})();
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<h2 class="content-head is-center">Contact Us!</h2>
<aside>
<p>
We would <em>love</em> to hear from you! </p>
<p>Please use the <b><em>Contact Form</em></b> to send us a message.
</p>
</aside>
<!-- START HERE -->
<link rel="stylesheet" href="https://unpkg.com/purecss#1.0.0/build/pure-min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<!-- Style The Contact Form How Ever You Prefer -->
<link rel="stylesheet" href="style.css">
<form class="gform pure-form pure-form-stacked" method="POST" data-email="" action="https://script.google.com/macros/s/AKfycbxud2vvVuUj0YXOasdO50lQwPJc3FnoTZXdNtgRdaYnl70kKDlRO6nS/exec">
<!-- change the form action to your script url -->
<div class="form-elements">
<fieldset class="pure-group">
<label for="name">Name: </label>
<input id="name" name="name" placeholder="What your Mom calls you" />
</fieldset>
<fieldset class="pure-group">
<label for="message">Message: </label>
<textarea id="message" name="message" rows="10" placeholder="Tell us what's on your mind..."></textarea>
</fieldset>
<fieldset class="pure-group">
<label for="email"><em>Your</em> Email Address:</label>
<input id="email" name="email" type="email" value="" required placeholder="your.name#email.com" />
</fieldset>
<fieldset class="pure-group">
<label for="color">Favourite Color: </label>
<input id="color" name="color" placeholder="green" />
</fieldset>
<fieldset class="pure-group honeypot-field">
<label for="honeypot">To help avoid spam, utilize a Honeypot technique with a hidden text field; must be empty to submit the form! Otherwise, we assume the user is a spam bot.</label>
<input id="honeypot" type="text" name="honeypot" value="" />
</fieldset>
<button class="button-success pure-button button-xlarge">
<i class="fa fa-paper-plane"></i> Send</button>
</div>
<!-- Customise the Thankyou Message People See when they submit the form: -->
<div class="thankyou_message" style="display:none;">
<h2><em>Thanks</em> for contacting us! We will get back to you soon!</h2>
</div>
</form>
<div class="toast" id="myToast" data-autohide="false">
<div class="toast-header">
<strong class="mr-auto text-primary">Toast Header</strong>
<small class="text-muted">5 mins ago</small>
<button type="button" class="ml-2 mb-1 close" data-dismiss="toast">×</button>
</div>
<div class="toast-body">
Some text inside the toast body
</div>
</div>
<button type="button" class="btn btn-primary show-toast">Show Toast</button>
<script>
$(document).ready(function() {
$(".show-toast").click(function() {
$("#myToast").toast('show');
});
});
</script>
<!-- Submit the Form to Google Using "AJAX" -->
<script data-cfasync="false" src="form-submission-hanler.js"></script>
<!-- END -->
You can add event on click of button and use reset() to reset the form values. Add following code in your script section:
$('.button-success').on('click', function(e){
e.preventDefault() //This stops page loading
$("#myToast").toast('show'); //Show toast
document.getElementsByName('data-form')[0].reset() //reset field values of the form
})
Add name parameter to your form tag to access it inside this function. (For ex: I have added name as 'data-form')
Related
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Checklist</title>
<link rel="stylesheet" type="text/css" href="./style.css">
<script src="script.js"></script>
</head>
<body>
<h1>Checklist</h1>
<form onsubmit="return isChecked()">
<div class="workout>">
<input type="checkbox" id="workout" name="todo1" value="workout">workout</input>
</div>
<div class="meeting">
<input type="checkbox" id="meeting" name="todo2" value="meeting">meeting</input>
</div>
<div class="lunch">
<input type="checkbox" id="lunch" name="todo3" value="lunch">lunch</input>
</div>
<div class="school">
<input type="checkbox" id="school" name="todo4" value="school">class</input>
</div>
<div>
<input class="submit" id="submit" type="submit" value="Submit"
onchange="document.getElementById('formName').submit()">
</div>
<!--<p id="msg"></p> (I tried using this approach and calling the msg within script but I received an error.)-->
</form>
</div>
</body>
<script>
function isChecked() {
var workout = document.getElementById('workout').checked;
var meeting = document.getElementById('meeting').checked;
var lunch = document.getElementById('lunch').checked;
var school = document.getElementById('school').checked;
var submit = document.getElementById('submit');
var text = document.getElementById('msg');
//My if/else statement alert works perfectly. However, with the presence of const submit, it doesn't work properly (I think it's interfering with my if/else statement). Removing the const submit section allows one to experience the if/else alert statement. The goal of this checklist is to be able to check one or all four checkboxes and have it return the "Enjoy your day" text. However, I would like for that message to cover the screen and be the only thing visible after hitting the submit button. I'm okay with receiving an alert box when it returns false. However, when it returns true, I would like for the message to cover the screen and for the checklist/checkboxes to disappear. I'm not sure where I'm getting my wires crossed.
if (workout == false && meeting == false && lunch == false && school == false) {
alert('Please check a box');
return false;
} else {
return true;
}
const submit = document.getElementById("submit");
submit.addEventListener("click", function (e) {
document.body.innerHTML = "<h1>Enjoy your day.</h1>";
});
}
</script>
</html>
enter image description here
enter image description here
You are declaring submit twice in the isChecked function. Omit one of the declaration.
Also, you are adding the event listener to the submit button after the return statement, which JS will ignore and won't append any onclick function.
The updated isChecked function should be
function isChecked() {
var workout = document.getElementById('workout').checked;
var meeting = document.getElementById('meeting').checked;
var lunch = document.getElementById('lunch').checked;
var school = document.getElementById('school').checked;
// Removed the submit variable
var text = document.getElementById('msg');
if (workout == false && meeting == false && lunch == false && school == false) {
alert('Please check a box');
return false;
}
const submit = document.getElementById("submit");
submit.addEventListener("click", function (e) {
document.body.innerHTML = "<h1>Enjoy your day.</h1>";
});
// Returning true after adding the event listener.
return true;
}
Just display the message since it is being called onsubmit
function isChecked() {
var workout = document.getElementById('workout').checked;
var meeting = document.getElementById('meeting').checked;
var lunch = document.getElementById('lunch').checked;
var school = document.getElementById('school').checked;
if (!workout && !meeting && !lunch && !school) {
alert('Please check a box');
} else {
document.body.innerHTML = "<h1>Enjoy your day.</h1>";
}
return false;
}
<h1>Checklist</h1>
<form onsubmit="return isChecked()">
<div class="workout>">
<input type="checkbox" id="workout" name="todo1" value="workout">workout</input>
</div>
<div class="meeting">
<input type="checkbox" id="meeting" name="todo2" value="meeting">meeting</input>
</div>
<div class="lunch">
<input type="checkbox" id="lunch" name="todo3" value="lunch">lunch</input>
</div>
<div class="school">
<input type="checkbox" id="school" name="todo4" value="school">class</input>
</div>
<div>
<input class="submit" id="submit" type="submit" value="Submit">
</div>
</form>
</div>
When users click submit, I've coded an error message to appear under each input field that is missing a value using DOM selectors. I also disabled the email file that opens when submit is clicked, using preventDefault().
However, when the user types into the text area, the messages don't disappear. I tried using a 'keydown' event, but I couldn't get it to work.
HTML code:
<body>
<header class="header">
<form action="mailto:me#fakeemail.com">
<fieldset>
<legend>Personal details</legend>
<p>
<label>
Full name:
<input type="text" name="fullname" id="fullname">
</label>
</p>
<p class="errormsg" id="nameerrormsg">Please enter your name above</p>
<p>
<label>
Street Address:
<input type="text" name="streetaddr" id="streetaddr">
</label>
</p>
<p class="errormsg" id="addrerrormsg">Please enter your street address</p>
</fieldset>
<input type="submit" value="Submit it!" class="submitIt" onsubmit="return checkForm();">
</form>
<br>
<script src="inline-error.js" charset="utf-8"></script>
<div class="returnHome">
Return Home
</div>
</header>
</body>
Javascript code:
var submitIt = document.querySelector(".submitIt");
submitIt.addEventListener("click", function checkForm(event) {
var fNameInput = document.querySelector("#fullname")
var streetAddInput = document.querySelector("#streetaddr")
if (fNameInput.value == "") {
var nameErrorMsg = document.querySelector("#nameerrormsg").style.display = "block";
event.preventDefault();
}
if (streetAddInput.value == "") {
var addrErrorMsg = document.querySelector("#addrerrormsg").style.display = "block";
event.preventDefault();
}
})
To see an immediate result in the code in its current state, hide the error messages before checking the input values.
var submitIt = document.querySelector('.submitIt');
submitIt.addEventListener('click', function checkForm(event) {
var nameErrorMsg = document.querySelector('#nameerrormsg');
var addrErrorMsg = document.querySelector('#addrerrormsg');
nameErrorMsg.style.display = 'none';
addrErrorMsg.style.display = 'none';
var fNameInput = document.querySelector('#fullname');
var streetAddrInput = document.querySelector('#streetaddr');
if (fNameInput.value == '') {
nameErrorMsg.style.display = 'block';
event.preventDefault();
}
if (streetAddrInput.value == '') {
addrErrorMsg.style.display = 'block';
event.preventDefault();
}
});
Having said that, here are some additional suggestions:
Use CSS for styling elements (not JavaScript)
Discourage inline JavaScript
Store DOM elements outside the scope of the event listener so you don't have to query the DOM every time you click
Consider utilizing the required attribute on the inputs for a quick win on styling
So...
<!-- form.html -->
<head>
<link rel="stylesheet" href="form.css">
</head>
<body>
<header class="header">
<form>
<fieldset>
<legend>Personal details</legend>
<p>
<label for="fullname">Full name:
<input type="text" name="fullname" id="fullname" required>
</label>
</p>
<p class="errormsg" id="nameerrormsg">Please enter your name above</p>
<p>
<label for="streetaddr">Street Address:
<input type="text" name="streetaddr" id="streetaddr" required>
</label>
</p>
<p class="errormsg" id="addrerrormsg">Please enter your street address</p>
</fieldset>
<input type="submit" value="Submit it!" class="submitIt">
</form>
</header>
<button id="returnhome">Return Home</button>
<script src="inline-error.js"></script>
</body>
/* form.css */
input:valid {
border: none;
}
input:invalid:required {
border: 1px solid red;
}
.errormsg {
display: none;
}
.show {
display: block;
}
// inline-error.js
var submitIt = document.querySelector('.submitIt');
var nameInput = document.querySelector('#fullname');
var nameError = document.querySelector('#nameerrormsg');
var addrInput = document.querySelector('#streetaddr');
var addrError = document.querySelector('#addrerrormsg');
var returnHome = document.querySelector('#returnhome');
returnHome.addEventListener('click', e => {
e.preventDefault();
history.back();
});
submitIt.addEventListener('click', event => {
const nameValue = nameInput.value;
const addrValue = addrInput.value;
if (!nameValue || !addrValue) {
event.preventDefault();
}
if (!nameValue) {
nameError.classList.add('show');
} else {
nameError.classList.remove('show');
}
if (!addrValue) {
addrError.classList.add('show');
} else {
addrError.classList.remove('show');
}
});
So, I have this contact form sending me a mail and updating my google sheet. I found this on GitHub. When I don't add the JS file I get a mail and an update. When I add the JS I get neither. I have tried with and without this script link when using JS but it does not work.
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous">
</script>
For security purpose I have removed my google sheet link and kept it as action="#" from form and because I have added my e-mail in my google sheet I can leave my data-email="" as it is.
I also don't get the thankyou message at the submission of the form when I have added my JS file, but without it I get confirmation displaying the details submitted.
There is a honeypot input label that is hidden by CSS and needs to be left blank for the form to be submitted successfully, avoiding spam.
It seems that there is some issue with the JS(duh!).
Please help!!!
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="contact form example">
<title>Contact Form Example</title>
</head>
<body>
<h2 class="content-head is-center">Contact Us!</h2>
<aside>
<p>
We would <em>love</em> to hear from you! </p>
<p>Please use the <b><em>Contact Form</em></b>
to send us a message.
</p>
</aside>
<!-- START HERE -->
<link rel="stylesheet" href="https://unpkg.com/purecss#1.0.0/build/pure-min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<!-- Style The Contact Form How Ever You Prefer -->
<link rel="stylesheet" href="style.css">
<form class="gform pure-form pure-form-stacked" method="POST" data-email=""
action="#">
<!-- change the form action to your script url -->
<div class="form-elements">
<fieldset class="pure-group">
<label for="name">Name: </label>
<input id="name" name="name" placeholder="What your Mom calls you" />
</fieldset>
<fieldset class="pure-group">
<label for="message">Message: </label>
<textarea id="message" name="message" rows="10"
placeholder="Tell us what's on your mind..."></textarea>
</fieldset>
<fieldset class="pure-group">
<label for="email"><em>Your</em> Email Address:</label>
<input id="email" name="email" type="email" value=""
required placeholder="your.name#email.com"/>
</fieldset>
<fieldset class="pure-group">
<label for="color">Favourite Color: </label>
<input id="color" name="color" placeholder="green" />
</fieldset>
<fieldset class="pure-group honeypot-field">
<label for="honeypot">To help avoid spam, utilize a Honeypot technique with a hidden text field; must be empty to submit the form! Otherwise, we assume the user is a spam bot.</label>
<input id="honeypot" type="text" name="honeypot" value="" />
</fieldset>
<button class="button-success pure-button button-xlarge">
<i class="fa fa-paper-plane"></i> Send</button>
</div>
<!-- Customise the Thankyou Message People See when they submit the form: -->
<div class="thankyou_message" style="display:none;">
<h2><em>Thanks</em> for contacting us!
We will get back to you soon!</h2>
</div>
</form>
<!-- Submit the Form to Google Using "AJAX" -->
<script data-cfasync="false" type="text/javascript" src="form-submission-handler.js"></script>
<!-- END -->
</body>
</html>
JS
(function() {
// get all data in form and return object
function getFormData(form) {
var elements = form.elements;
var honeypot;
var fields = Object.keys(elements).filter(function(k) {
if (elements[k].name === "honeypot") {
honeypot = elements[k].value;
return false;
}
return true;
}).map(function(k) {
if(elements[k].name !== undefined) {
return elements[k].name;
// special case for Edge's html collection
}else if(elements[k].length > 0){
return elements[k].item(0).name;
}
}).filter(function(item, pos, self) {
return self.indexOf(item) == pos && item;
});
var formData = {};
fields.forEach(function(name){
var element = elements[name];
// singular form elements just have one value
formData[name] = element.value;
// when our element has multiple items, get their values
if (element.length) {
var data = [];
for (var i = 0; i < element.length; i++) {
var item = element.item(i);
if (item.checked || item.selected) {
data.push(item.value);
}
}
formData[name] = data.join(', ');
}
});
// add form-specific values into the data
formData.formDataNameOrder = JSON.stringify(fields);
formData.formGoogleSheetName = form.dataset.sheet || "responses"; // default sheet name
formData.formGoogleSendEmail
= form.dataset.email || ""; // no email by default
return {data: formData, honeypot: honeypot};
}
function handleFormSubmit(event) { // handles form submit without any jquery
event.preventDefault(); // we are submitting via xhr below
var form = event.target;
var formData = getFormData(form);
var data = formData.data;
// If a honeypot field is filled, assume it was done so by a spam bot.
if (formData.honeypot) {
return false;
}
disableAllButtons(form);
var url = form.action;
var xhr = new XMLHttpRequest();
xhr.open('POST', url);
// xhr.withCredentials = true;
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
form.reset();
var formElements = form.querySelector(".form-elements")
if (formElements) {
formElements.style.display = "none"; // hide form
}
var thankYouMessage = form.querySelector(".thankyou_message");
if (thankYouMessage) {
thankYouMessage.style.display = "block";
}
}
};
// url encode form data for sending as post data
var encoded = Object.keys(data).map(function(k) {
return encodeURIComponent(k) + "=" + encodeURIComponent(data[k]);
}).join('&');
xhr.send(encoded);
}
function loaded() {
// bind to the submit event of our form
var forms = document.querySelectorAll("form.gform");
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener("submit", handleFormSubmit, false);
}
};
document.addEventListener("DOMContentLoaded", loaded, false);
function disableAllButtons(form) {
var buttons = form.querySelectorAll("button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].disabled = true;
}
}
})();
CSS
body {
margin: 2em;
}
aside {
background: #1f8dd6; /* same color as selected state on site menu */
padding: 0.3em 1em;
border-radius: 3px;
color: #fff;
margin-bottom: 2em;
}
textarea {
width: 100%;
}
.content-head {
font-weight: 400;
text-transform: uppercase;
letter-spacing: 0.1em;
margin: 2em 0 1em;
}
.is-center {
text-align: center;
}
.button-success {
color: white;
border-radius: 4px;
text-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
background: rgb(28, 184, 65); /* this is a green */
}
.button-xlarge {
font-size: 125%;
}
button {
float: right;
}
#name, #email {
width: 50%;
}
.honeypot-field {
display: none;
}
Hello and thank you for your time.
I have a form with the id payment and a submit button, but there seems to be a mistake in my JavaScript, as I only get the alert message but the page still submits if I input a wrong name like a row of hash symbols #######. the code below is exactly how it is in my file.
// form validation, makes sure that the user inputs the correct data types.
function validateinput(event){
var email = document.getElementById('email').value;
var firstname = document.getElementById('firstname').value;
var lastname = document.getElementById('lastname').value;
var message = document.getElementById('message').value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
var firstnameFilter = /^([" "a-zA-Z.-])+$/;
var lastnameFilter = /^([" "a-zA-Z.-])+$/;
var messageFilter = /^([" "a-zA-Z0-9_.-])+$/;
if (!emailFilter.test(email)) {
alert('!Enter a email. Or enter a valid email address.');
document.getElementById('payment').addEventListener('onsubmit', function(event) {event.preventDefault();});
return false;
}
if (!firstnameFilter.test(firstname)) {
alert('!Enter a first name. Or enter a valid name.');
document.getElementById('payment').addEventListener('onsubmit', function(event) {event.preventDefault();});
return false;
}
if (!lastnameFilter.test(lastname)) {
alert('!Enter a last name. Or enter a name., only letters');
document.getElementById('payment').addEventListener('onsubmit', function(event) {event.preventDefault();});
return false;
}
if (!messageFilter.test(message)) {
alert('!Enter a message.');
document.getElementById('payment').addEventListener('onsubmit', function(event) {event.preventDefault();});
return false;
}
alert ('Your order was submited')
}
document.getElementById('payment').addEventListener("submit", validateinput)
have also tried other methods thought they do not seem too work on this page but works on others ?
Like changing the var names and id,s in this one i am using on my contact page
function validateinput(event){
var address1 = document.getElementById('address1').value;
var postcode = document.getElementById('postcode').value;
var address1Filter = /^([" "a-zA-Z0-9_.-])+$/;
var postcodeFilter = /^([" "a-zA-Z0-9_.-])+$/;
var formValid = true;
if (!address1Filter.test(address1)) {
alert('!Enter an address. Or enter a valid address., only letters and numbers');
formValid = false;
event.preventDefault();
return false;
}
if (!postcodeFilter.test(postcode)) {
alert('!Enter a postcode. Or enter a valid postcode., only letters and numbers');
formValid = false;
event.preventDefault();
return false;
}
alert ('Your order was submited')
}
document.getElementById('payment').addEventListener("submit", validateinput)
So what am I doing wrong ?
the html
<!doctype html>
<!-- name: Edwin martin -date: 30/11/2015 -task: a form with split up inputs using the
<fieldset> & <legend> tags -->
<html lang="en">
<head>
<title>contact</title>
<script type="text/javascript" src="scripts/contact2.js"> </script>
<!-- ensures the document is using the correct char set -->
<meta charset="utf-8">
<meta name="description" content="contact page">
<link rel="icon" href="images/fav.png" type="image/png"/>
<!--
The below section looks like a comment, but it's a conditional include statement.
It's ignored by all browsers except IE9. html5shiv is a library that fixes some HTML5
IE bugs.
-->
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- pulls in the styles sheet -->
<link rel="stylesheet" href="styles/indexstyles.css">
</head>
<body onload="main()">
<!-- start of the form, id form sets the position, size, border style and color -->
<div id="form2">
<!-- sets the link position, list and text style of the header, id head color sets the background color for the division around the header -->
<div id="head">
<header id="headcolor">
<div id="toplinks">
<ul>
<li class="tl"> <input type="button" class="topbutton" name="b1" value="Index" onclick="location.href='index.html'"> </li>
<li class="tl"> <input type="button" class="topbutton" name="b1" value="order" onclick="location.href='order.html'"> </li>
</ul>
</div> <br>
<br>
</header>
<h1 id="title"> Contact </h1>
<p> southampton solent pizzas: southampton solent university branch. E Park Terrace, Southampton, Hampshire SO14 0YN </p>
</div>
<div id="map"> </div>
<!-- id payment sets the input boxs background color , position and border for invaild - vaild -->
<form id="payment">
<!-- Contact Information section -->
<fieldset>
<legend> Personal Information </legend>
<p> <label> First Name(*): </label> <input type="text" name="first_name" id="firstname" placeholder="enter a first name" class="add1"></p>
<p> <label> Last Name(*): </label> <input type="text" name="last_name" id="lastname" placeholder="enter a last name" class="add1"></p>
<p> <label> Email(*): </label> <input type="text" name="email" id="email" placeholder="enter a email" class="add1"></p>
<p> <label>Phone Number: </label> <input type="text" name="phone" id="phone"></p>
<p> <label> message(*): </label> <input type="text" name="message" id="message" placeholder="enter your message" class="add1"></p>
</fieldset>
<!-- Submit button -->
<input type="submit" class="submit_button">
<input type="reset" class="reset_button">
</form>
</div>
<script type="text/javascript" src="scripts/contact.js"> </script>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script>
</body>
</html>
i also have another JS script as you can see from the two different links. but even if i remove that link - code there form still submits with the wrong input, as this code just reads a empty input
//onload callback function
function main() {
console.log("in main function");
var myForm = document.getElementById("payment");
myForm.addEventListener("submit",validateForm);
}
//validate callback function
function validateForm(event) {
var formValid = true;
var myForm = document.getElementById("payment");
if (myForm.first_name.value == "") {
formValid = false;
//display error message
document.getElementById("firstname").className += " formInvalid"; //add the class .formInvalid
//stop form from submitting
event.preventDefault();
}
if (myForm.last_name.value == "") {
formValid = false;
//display error message
document.getElementById("lastname").className += " formInvalid"; //add the class .formInvalid
//stop form from submitting
event.preventDefault();
}
if (myForm.email.value == "") {
formValid = false;
//display error message
document.getElementById("email").className += " formInvalid"; //add the class .formInvalid
//stop form from submitting
event.preventDefault();
}
if (myForm.message.value == "") {
formValid = false;
//display error message
document.getElementById("message").className += " formInvalid"; //add the class .formInvalid
//stop form from submitting
event.preventDefault();
}
}
document.getElementById('payment').addEventListener("submit", validateinput), the problem is that you want to pass an argument to the validateinput method, but you can't do it that way, to pass arguments to a callback method reference, you should wrap it in an anonymous function like this.
document.getElementById('payment').addEventListener("submit", function(event) {
validateinput(event);
});
I think you're over complicating your Javascript. If you change your submit to call the function directly you'll have an easier time handling the negative states.
<input type="submit" onclick="return validateinput();" class="submit_button">
You'll need to modify the validateinput function slightly since you won't have event being passed in anymore.
Since the NATIVE sandbox on google apps script is deprecated, I'm switching to IFRAME, which has caused some issues.
The basic outline of the app is that it should allow a user to fill in some information and upload a file (it also makes sure all required fields are completed). Upon submission (by clicking a button), the file should be uploaded to a folder in google drive and a spreadsheet should be updated with the user's information. When I'm in NATIVE, everything works fine. When I set it to IFRAME, nothing happens when I click the submit button.
This is a similar issue to here and here, but neither of them directly address my problem. I also tried following the Google Guide but it didn't help.
Here is my server.gs script:
function doGet(e) {
return template = HtmlService.createHtmlOutputFromFile('form.html').setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function uploadFiles(form) {
try {
var dropbox = "Applications";
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
var CV = form.CV;
var foldername = form.myLastName + ", " + form.myFirstName;
var myFolder = folder.createFolder(foldername);
var file_CV = myFolder.createFile(CV);
var CV_url = file_CV.getUrl();
var sheet_return = addApplicant(form, CV_url);
return "Thank you for your submission."
} catch (error) {
return error.toString();
}
}
function addApplicant(form, CV_url) {
try {
var d = new Date()
var ss = SpreadsheetApp.openByUrl(***INSERT URL TO GOOGLE SHEETS PAGE***);
SpreadsheetApp.setActiveSpreadsheet(ss);
SpreadsheetApp.setActiveSheet(ss.getSheets()[0]);
var sheet = SpreadsheetApp.getActiveSheet();
if (form.visa != "Yes"){
form.visa = "No"
}
sheet.appendRow([d, form.myFirstName, form.myLastName, form.myEmail, form.visa, CV_url]);
} catch (error) {
return error.toString();
}
}
Here is my form.html script:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<!-- You can also include your own CSS styles -->
<link href='https://fonts.googleapis.com/css?family=Bitter' rel='stylesheet' type='text/css'>
<style type="text/css">
.warning {border: 1px solid red !important; background: #fdecb2 !important;}
.hideClass {display:none;}
</style>
<div class="form-style-10">
<title> Application </title>
<form id="myForm" name="myForm">
<fieldset class="fields">
<div class="section"> Personal Information </div>
<div class="inner-wrap">
<label for="myFirstName"> First Name* </label>
<input type="text" id="myFirstName" name="myFirstName" placeholder="" required />
<label for="myLastName"> Last Name* </label>
<input type="text" name="myLastName" placeholder="" required />
<label for="myEmail"> Email* </label>
<input type="email" name="myEmail" placeholder="" required />
<span class="visa-checkbox">
Check if you will require visa assistance. <input type="checkbox" name="visa" value="Yes" />
</span>
</div>
</fieldset>
<fieldset class="fields">
<div class="section"> Documents (pdf format is preferred) </div>
<div class="inner-wrap">
<label for="CV"> CV* </label>
<input type="file" name="CV" required />
</div>
</fieldset>
<p> </p>
<p id="incompleteWarning" class="hideClass"> Please check for incomplete fields and re-submit. </p>
<p id="bePatient" class="hideClass"> Please be patient while the files are being uploaded. Do not close or refresh the form. </p>
<input id="submitbutton" type="button" value="Submit Application" />
</form>
<div id="output" class="hideClass">
<span id="ThankYou" >Thank you for taking the time to complete the application.
</span>
</div>
</div>
<script type="text/javscript">
document.getElementById('submitbutton').addEventListener("click", validatefunction);
function validatefunction() {
document.getElementById('submitbutton').val = 'Submitting...';
//check for required fields
var j = 0;
var form = document.getElementById('myForm');
var elem = form.elements;
for (var i = 0; i < elem.length; i++){
elem[i].className = "";
if (elem[i].value === "" && elem[i].hasAttribute('required')){
elem[i].className = "warning";
j++;
}
}
if (j === 0) {
var btn = document.getElementById('submitbutton');
btn.disabled = true;
document.getElementById('incompleteWarning').style.display = 'none';
document.getElementById('bePatient').style.display = 'inline';
google.script.run.withSuccessHandler(fileUploaded).uploadFiles(this.parentNode);
} else{
document.getElementById('submitbutton').val = 'Submit Application';
document.getElementById('incompleteWarning').style.display = 'inline';
document.getElementById('incompleteWarning').style.color = 'red';
}
};
</script>
<script>
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').style.display = 'inline';
}
</script>
<style>
input { display:block; margin: 20px; }
</style>
</body>
</html>
Change:
<script type="text/javscript">
To:
<script language="javascript">
I don't know why it doesn't like type="text/javscript"