Serverless Contact form issue html css ajax js - javascript

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;
}

Related

Display toast and clear form after submit

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')

HTML Form Using JavaScript Valildation

I working on Javascript validation task as i am beginner in Javascript i was stuck in Js validation code codepen.Can, Anyone Please help out of this and point me in right direction.
Thanks in advance.
jQuery(document).ready(function($) {
function formValidation() {
var firstname = document.getElementById('product');
if (firstname.value.length == 0) {
document.getElementById('head').innerText = "* All fields are mandatory *";
firstname.focus();
return false;
}
if (inputAlphabet(firstname, "* For your name please use alphabets only *")) {
return true;
}
return false;
}
function textNumeric(inputtext, alertMsg) {
var numericExpression = /^[0-9]+$/;
if (inputtext.value.match(numericExpression)) {
return true;
}
else {
document.getElementByClass('price').innerText = alertMsg;
inputtext.focus();
return false;
}
}
function inputAlphabet(inputtext, alertMsg) {
var alphaExp = /^[a-zA-Z]+$/;
if (inputtext.value.match(alphaExp)) {
return true;
}
else {
document.getElementById('product').innerText = alertMsg;
inputtext.focus();
return false;
}
}
});
body {
background: #f5f5f5;
}
.product-container {
display: flex;
justify-content: center;
align-items: center;
padding: 100px;
}
input#product {
max-width: 200px;
padding: 5px 20px;
}
input.price {
max-width: 227px;
padding: 5px 4px;
width: 100%;
}
input.qnty {
max-width: 235px;
width: 100%;
padding: 5px 4px;
}
input[type="submit"] {
font-size: 14px;
font-family: 'Roboto', sans-serif;
font-weight: 500;
color: #000000;
padding: 5px 10px;
letter-spacing: 0.6px;
}
<!DOCTYPE html>
<html>
<head>
<title>Product Order</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
<script src="custom.js"></script>
</head>
<body>
<div class="product-container">
<form action="submit" method="POST">
Product Name: <input type="text" name="name" value="" required id="product" ><br><br>
Unit Price: <input type="number" name="Price" value= "" required class="price" pattern="\d+(\.\d{2})?"><br><br>
Quantity: <input type="number" name="Quantity" value="" min="1" max="10" required class="qnty price"><br><br>
<input type = "submit" name = "submit" value = "Get Total Amount">
</form>
</div>
</body>
</html>
You're doing the same thing I was doing when I started using jQuery... mixing JavaScript with jQuery.
You don't need to create a function to validate the form. I'd first change your submit button to this:
<button type="button" id="submitButton">Submit</button>
Then use jQuery to listen for the button click:
$('#submitButton').on('click', function() {
var product = $('#product').val();
var price = $('.price').val();
var name = $('#name').val();
// check if name input has a value, if blank, then display error message
if(name == "") {
alert('You must enter a name');
return false;
}
if(product == '//whatever you want to check here') {
// display message
}
if(price == '// check if the input is blank') {
// return error message
}
else {
// do something
}
});
The if/else inside your button click is your validation.
I see a ton of errors in your very small code. Your Jquery code looks very bad. You are creating functions but never using them, You don't have to create functions for form validation. You can use Jquery event listeners to check if the user has performed some action like (submit, Focus, Blur etc.,) and when you receive the event you have to perform an action and clearly innerText does not work on input boxes. Go through this article on form validation using Jquery.
You should do basic google search before posting a question here.

PHP Form Validation with Javascript doesnt stop on return false

I have been trying to make a simple HTML form validation via Javascript
I have been struggling with this for a while now over a few examples, And no matter what I follow, My index page keeps loading after the button click on the form, I believe that I have put return false in the correct locations to break the rest of code execution, Any ideas why this is so? "My" code is below
Note: I have tried the novalidate attribute with the form, this deactivates the browser's validation but still sends me through to my index page, The ideal functionality should not load the index page and stay on the register page with warnings below the correct input fields
index.php
<?php
if (isset($_POST["register"]))
{
$user = $_POST["username"];
echo "Welcome ".$user;
}
?>
register.php
<!DOCTYPE html>
<html>
<head>
<title>Form validation with javascript</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="wrapper">
<form novalidate method="POST" action="index.php" onsubmit="return Validate()" name="vform">
<div>
<input type="text" name="username" class="textInput" placeholder="Username">
<div id="name_error" class="val_error"></div>
</div>
<div>
<input type="email" name="email" class="textInput" placeholder="Email">
<div id="email_error" class="val_error"></div>
</div>
<div>
<input type="password" name="password" class="textInput" placeholder="Password">
</div>
<div>
<input type="password" name="password_confirmation" class="textInput" placeholder="Password confirmation">
<div id="password_error" class="val_error"></div>
</div>
<div>
<input type="submit" value="Register" class="btn" name="register">
</div>
</form>
</div>
</body>
</html>
<!-- Adding javascript -->
<script type="text/javascript">
// GETTING ALL INPUT TEXT OBJECTS
var username = document.forms["vform"]["username"];
var email = document.forms["vform"]["email"];
var password = document.forms["vform"]["password"];
var password_confirmation = document.forms["vform"]["password_confirmation"];
// GETTING ALL ERROR DISPLAY OBJECTS
var name_error = document.getElementId("name_error");
var email_error = document.getElementId("email_error");
var password_error = document.getElementId("password_error");
// SETTING ALL EVENT LISTENERS
username.addEventListener("blur", nameVerify, true);
email.addEventListener("blur", emailVerify, true);
password.addEventListener("blur", passwordVerify, true);
// Validation Function
function Validate(){
// Username Validation
if (username.value == ""){
username.style.border = "1px solid red";
name_error.textContent = "Username is required";
username.focus();
return false;
}
// Email Validation
if (email.value == ""){
email.style.border = "1px solid red";
email_error.textContent = "email is required";
email.focus();
return false;
}
// Password Validation
if (password.value == ""){
password.style.border = "1px solid red";
password_error.textContent = "password is required";
password.focus();
return false;
}
// check if the two passwords match
if (password.value != password_confirmation.value)
{
pasword.style.border = "1px solid red";
pasword_confirmation.style.border = "1px solid red";
password_error.innerHTML = "The two passwords dont match";
return false;
}
}
// event handler functions
function nameVerify(){
if (username.value != "")
{
username.style.border = "1px solid #5E6E66";
name_error.innerHTML = "";
return true;
}
}
function emailVerify(){
if (email.value != "")
{
email.style.border = "1px solid #5E6E66";
email_error.innerHTML = "";
return true;
}
}
function passwordVerify(){
if (passwprd.value != "")
{
passwprd.style.border = "1px solid #5E6E66";
passwprd_error.innerHTML = "";
return true;
}
}
</script>
style.css
#wrapper{
width: 35%;
margin: 50px auto;
padding: 20px;
background: #EFFFE0;
}
form{
width: 50%;
margin: 100px auto;
}
form div{
margin: 3px auto;
}
.textInput{
margin-top: 2px;
height: 28px;
border: 1px solid #5E6E66;
font-size: 16px;
padding: 1px;
width: 100%;
}
.btn{
padding: 7px;
width: 100%;
}
.val_error{
color: #FF1F1F;
}
Thanks a bunch for any help you can provide!
Assign an id to your form, attach form submit event to it and if validations get fails then you can use event.preventDefault(); to stop the submission of form.
Try the code below.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<form action="your_file_name.php" method="post" id="myForm">
First name:<br>
<input type="text" name="firstname" id="firstname">
<br>
Last name:<br>
<input type="text" name="lastname" id="lastname" >
<br><br>
<input type="submit" value="Submit">
</form>
$( "#myForm" ).submit(function(event) {
if($("#firstname").val()== "" || $("#lastname").val()== "") //Your validation conditions.
{
alert("Kindly fill all fields.");
event.preventDefault();
}
//submit the form.
});
</script>
</html>

Update from NATIVE sandbox to IFRAME; button not working

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"

Hide Show City and State when zip is populated

javascript: I want to show city and state when the zip is filled in. I have the the geo location working but now I just want city and state to show when the zip is filled in.
This is my HTML:
<label for="city">City</label>
<input size="20" placeholder="Town or City" name="city" id="city" type="text">
<br>
<label for="state">State</label>
<input size="10" placeholder="State/Province" name="state" id="state" type="text">
And this is my JavaScript:
zip.addEventListener("change", getGeo);
function getGeo(e){
// make an send an XmlHttpRequest
var x = new XMLHttpRequest();
x.open("GET","http://maps.googleapis.com/maps/api/geocode/json?address="+this.value,true);
x.send();
// set up a listener for the response
x.onreadystatechange=function(){
if (this.readyState==4 && this.status==200){
var c = JSON.parse(this.response).results[0].address_components[1].long_name;
//alert(c);
var s = JSON.parse(this.response).results[0].address_components[2].short_name;
//alert(s);
if (c) {
city.value = c;
}
if (s) {
state.value = s;
}
//document.getElementById("output").innerHTML = o;
var l = JSON.parse(this.response).results[0].geometry.location;
if (l.lat) {
lat.value = l.lat;
}
if (l.lng) {
lon.value = l.lng;
}
}
}
}
It's all in this jsfiddle http://jsfiddle.net/lakenney/gad7ntgk/
Looks like you already have a good start, but this example might help a bit. Run the code snippet and enter a postal code or city name. I kept it very simple, but you could check the data array length. When equal to 1 you have a match and could display geo location and other into on the page.
Keep in mind that you're doing a cross domain ajax call ... which will fail in IE < 10. Lots of questions about that on SO if you need help.
<!DOCTYPE HTML>
<html>
<head>
<title>Demo</title>
<style type="text/css">
#container {position: relative; }
#location {width: 20em; border: 1px steelblue solid;}
#results { border: 1px gray solid; padding: 2px; position: absolute;background-color:aliceblue;}
#results ul { list-style: none; padding: 0; }
#results ul li {padding: 2px; color: dimgray; }
</style>
</head>
<body>
<div id="container">
Enter a city or postal code:<br>
<input id="location" type="text" onKeyup="getLocation()" value="London">
<div id="results"></div>
</div>
<script type="text/javascript">
function getLocation( ) {
var value, xhr, html, data, i;
value = document.getElementById('location').value;
if (value.length < 2) return;
xhr = new XMLHttpRequest();
xhr.open("GET", "http://maps.googleapis.com/maps/api/geocode/json?address=" + value, true );
xhr.onreadystatechange = function() {
if (xhr.readyState==4 && xhr.status==200) {
data = JSON.parse(xhr.responseText);
html = '';
for(i=0; i< data.results.length; i++ ) {
html += '<li>' + data.results[i].formatted_address;
}
document.getElementById('results').innerHTML = '<ul>' + html + '</ul>';
}
}
xhr.send();
}
getLocation();
document.getElementById('location').focus();
</script>
</body>
</html>
See updated jsfiddle.
http://jsfiddle.net/gad7ntgk/3/
Problem that you had is that this HTML was commented out:
<!--<label for="city">City</label>
<input size="20" placeholder="Town or City" name="city" id="city" type="text">
<br>
<label for="state">State</label>
<input size="10" placeholder="State/Province" name="state" id="state" type="text">-->
And when values returned the assigning of value should be:
document.getElementById('city').value = c;

Categories

Resources