I'm trying to swap visibility of 2 elements based on a drop-down selection in the form.
If user selects any of the first 6 items, the "Message" area remains.
If user selections last item "Reproduction Rights", then "Message" disappears and is swapped with "Rights message" div.
I've got it working with the repro rights showing/hiding, but not the message box. I'm new to java, so pardon my ignorance. Here's the full page code or view at Paul-Rand.com:
Got it working with this code, but is there a cleaner way to do it?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Paul-Rand.com :: Contact Us</title>
{embed=site/meta}
<link rel="stylesheet" type="text/css" href="{stylesheet=styles/twocolumn}" />
<link rel="stylesheet" type="text/css" href="{stylesheet=styles/global}" />
<script type="text/javascript" src="{path=scripts/livevalidation_standalone}"></script>
<script type="text/javascript">
// <![CDATA[
function display(obj,id1,id2) {
txt = obj.options[obj.selectedIndex].value;
document.getElementById(id1).style.display = 'none';
document.getElementById(id2).style.display = 'none';
if ( txt.match(id1) ) {
document.getElementById(id1).style.display = 'block';
}
if ( txt.match(id2) ) {
document.getElementById(id2).style.display = 'block';
}
}
// ]]>
</script>
</head>
<body>
{embed="site/mainNav"}
<div id="container">
<div id="centercontent">
<h1>Contact Us</h1>
<div class="form-left">
<p>To send us a message, please fill out the form below. We'll get back to you shortly!</p>
{exp:freeform:form
required="name|email|message"
collection="Contact Form"
return="site/success"
notify="dlewandowski38#yahoo.com"
template="randContact"
file_upload="Email attachments"
send_attachment="yes" }
<label>Name / Company Name <em>(required)</em>
<br style="clear:both">
<span><input type="text" name="name" id="Name" class="formMediumText"/></span>
</label>
<script type="text/javascript">var Name = new LiveValidation('Name');Name.add(Validate.Presence);</script>
<label>Email <em>(required)</em>
<br style="clear:both">
<span><input type="text" name="email" id="Email" class="formMediumText"/></span>
<script type="text/javascript">var Email = new LiveValidation('Email');Email.add(Validate.Email );</script>
</label>
<label>Regarding
<br style="clear:both">
<span>
<select name="regarding" id="Regarding" class="formMediumText" onchange="display(this,'subject','Reproduction Rights');">
<option value="subject">General Inquiry</option>
<option value="subject">Suggestion for the site</option>
<option value="subject">Problem with the site</option>
<option value="subject">Work to Share</option>
<option value="subject">Story to Share</option>
<option value="subject">Pictures to Share</option>
<option value="Reproduction Rights">Reproduction Rights</option>
</select>
</span>
</label>
<div id="Reproduction Rights" style="display: none; float:left;background-color: #ff9900; padding: 20px;">
<h4 style="text-transform: uppercase; padding: 0; margin:0;">Reproduction rights are granted through the Paul Rand estate only.</h4>
<p style="padding: 0; margin: 0;">Contact the Yale Archives with a detailed description of your planned usage and they will process your request.</p>
</div>
<div id="subject" style="display: none">
<label>Message
<br style="clear:both">
<span>
<textarea cols="24" rows="12" name="message" id="Message" class="formMediumText"></textarea>
</span>
</label>
</div>
<br style="clear:both"/>
<hr/>
<h2 style="margin-bottom:-18px">Help the site grow</h2>
<h5 style="margin-bottom:-6px">Have a piece of Paul Rand work that's not seen on the site? Share it! </h5>
<p>Send your files (any image type, 800px wide or larger), your name and website (if available). I'll add it to the appropriate gallery and give you credit for your addition.</p>
<p>Your contributions are GREATLY APPRECIATED!</p>
<br/>
<label for="file" style="float:left;">Share a File (up to 5 per message):</label>
<span><input type="file" name="file1" id="file1" class="formPicBrowse"/></span>
<span><input type="file" name="file2" id="file2" class="formPicBrowse"/></span>
<span><input type="file" name="file3" id="file3" class="formPicBrowse"/></span>
<span><input type="file" name="file4" id="file4" class="formPicBrowse"/></span>
<span><input type="file" name="file5" id="file5" class="formPicBrowse"/></span>
<br style="clear:both"/>
<br/>
{if captcha}
<label>For security, please enter the word you see below:
<br style="clear:both">
<p style="width:160px;">{captcha}</p>
<span><input type="text" name="captcha" onfocus="if(this.value == 'Security Code') { this.value = ''; }" value="Security Code" id="Captcha" class="formMediumText" style="width:130px" /></span>
<script type="text/javascript">var Captcha = new LiveValidation('Captcha');Captcha.add(Validate.Presence);</script>
</label>
{/if}
<br style="clear:both"/>
<br/>
<p><input type="submit" name="submit" value="Send" class="buttons" style="font-size:18px; padding-top:8px;"/></p>
{/exp:freeform:form}
</div>
<script type="text/javascript">
var Name = new LiveValidation( 'Name', {onlyOnSubmit: true } );
Name.add( Validate.Presence );
var Email = new LiveValidation( 'Email', {onlyOnSubmit: true } );
Email.add( Validate.Presence );
var Message = new LiveValidation( 'Message', {onlyOnSubmit: true } );
Message.add( Validate.Presence );
var Captcha = new LiveValidation( 'Captcha', {onlyOnSubmit: true } );
Captcha.add( Validate.Presence );
</script>
</div>
</div>
{embed=site/bottomSection}
{embed=site/footer}
{embed=site/googleTracking}
</body>
</html>
For start it's good manners to clean your code to contain only the necessary bits before you post it here. It's difficult to wade through all of it in search of the relevant bits.
This isn't a JavaScript problem as such, just a plain logic issue. So what you want to do is a switch. If user selected option a set div 1 visible and div 2 invisible. If user selected option b do the opposite. Below is the modified display function
function display(obj) {
txt = obj.options[obj.selectedIndex].value;
if (txt.match("Reproduction Rights")) {
document.getElementById("Reproduction Rights").style.display = 'block';
document.getElementById("MessageDiv").style.display = 'none';
}
else {
document.getElementById("Reproduction Rights").style.display = 'none';
document.getElementById("MessageDiv").style.display = 'block';
}
}
and the HTMLto go with it. Two points to notice about this. You don't need the call to the hide() function in the onchange event handler, the display function is a switch, it'll do all the work. I also added a wrapping div with an id of MessageDiv to allow hiding both the message box and the text accompanying the message box. If the text isn't supposed to be hidden then by all means leave the div out.
<label>Regarding
<br style="clear:both">
<span><select name="regarding" id="Regarding" class="formMediumText" onchange="display(this, 'Reproduction Rights');">
<option value="General Inquiry">General Inquiry</option>
<option value="Suggestion for the site">Suggestion for the site</option>
<option value="Problem with the site">Problem with the site</option>
<option value="Work to Share">Work to Share</option>
<option value="Story to Share">Story to Share</option>
<option value="Pictures to Share">Pictures to Share</option>
<option value="Reproduction Rights">Reproduction Rights</option>
</select></span>
</label>
<div id="Reproduction Rights" style="display: none; float:left;background-color: #ff9900; padding: 20px;">
<h4 style="text-transform: uppercase; padding: 0; margin:0;">Reproduction rights are granted through the Paul Rand estate only.</h4>
<p style="padding: 0; margin: 0;">Contact the Yale Archives with a detailed description of your planned usage and they will process your request.</p>
</div>
<div id="MessageDiv">
<label>
Message <em>(required)</em>
<br style="clear:both">
<span><textarea cols="24" rows="12" name="message" id="Message" class="formMediumText"></textarea><script type="text/javascript">var Message = new LiveValidation('Message');Name.add(Validate.Presence);</script>
</span>
</label>
</div>
Related
I have all of my other fields validating as I expect, but when I add in my JS to validate the select options, my page then just reloads once I hit submit. I have tried multiple ways to get the select options to validate, but I am failing to find a solution. I MUST use plain JS to validate the entire form, as per project requirements, and I am displaying an error message below each field in a span that doesn't contain any user input. I will post my JS below, and I can post my HTML if needed. I added in some extra spaces between my select area code to hopefully help with readability.
document.addEventListener("DOMContentLoaded", function (event) {
alert("This page is best viewed with JavaScript enabled");
});
function validate() {
// NEW: move this way up here so all validations can affect its value:
var formValid = true;
// function to check if a name has been entered
var name = document.getElementById('name').value;
if (name == null || name.trim() == "") {
document.getElementById('nameerror').innerHTML = "Please enter your full name";
formValid = false;
} else {
document.getElementById('nameerror').innerHTML = "";
}
// function to check if an email has been entered
var email = document.getElementById('email').value;
if (email == null || email.trim() == "") {
document.getElementById('emailerror').innerHTML = "Please enter your email address";
formValid = false;
} else {
document.getElementById('emailerror').innerHTML = "";
}
// function to check if a telephone number has been provided
var phone = document.getElementById('phone').value;
if (phone == null || phone.trim() == "") {
document.getElementById('phoneerror').innerHTML = "Please enter your telephone number";
formValid = false;
} else {
document.getElementById('phoneerror').innerHTML = "";
}
//validate the select options
var select = document.getElementById('select').value;
if (select == '') {
document.getElementById('selecterror').innerHTML = "Please make a selection";
formValid = false;
} else {
document.getElementById('selecterror').innerHTML = "";
}
//function to validate the textarea field
var name = document.getElementById('textarea').value;
if (name == null || name.trim() == "") {
document.getElementById('textareaerror').innerHTML = "Please enter additional info";
formValid = false;
} else {
document.getElementById('textareaerror').innerHTML = "";
}
// function to validate if any radio button has been selected
var radios = document.getElementsByName('radio');
var radiosValid = false;
var i = 0;
while (!radiosValid && i < radios.length) {
if (radios[i].checked) radiosValid = true;
i++;
}
if (!radiosValid) {
document.getElementById('radioerror').innerHTML = "(Please check one)";
formValid = false;
} else {
document.getElementById('radioerror').innerHTML = "";
}
// function to confirm if any checkbox has been checked
var checkboxes = document.getElementsByName('checkbox');
var checkboxesValid = false;
var j = 0;
while (!checkboxesValid && j < checkboxes.length) {
if (checkboxes[j].checked) checkboxesValid = true;
j++;
}
if (!checkboxesValid) {
document.getElementById('checkboxerror').innerHTML = "(Please select at least one)";
formValid = false;
} else {
document.getElementById('checkboxerror').innerHTML = "";
}
// now that all validations have run, return the conclusion
alert("The form has been submitted!");
return formValid;
}
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Contact Us</title>
<style>
.contact-header {
font-family: cursive;
text-align: center;
font-size: 50px;
color: darkred;
}
form {
font-weight: bold;
text-align: center;
}
.contact {
font-weight: normal;
}
.checkbox input {
margin: 0 10px 0;
}
textarea {
width: 20%;
height: 5rem;
}
.sendRequest {
text-align: center;
}
</style>
<!--link to bootstrap css-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<!--link for icons-->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
<!--link to external stylesheet-->
<link href="restaurantStyles.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
<header>
<div class="jumbotron name-font">
<h1 class="display-4">Dan's Cakes</h1>
<hr class="my-4">
<p class="lead">BIG NEWS!! Dan's Cakes will be opening a new restaurant VERY soon!!!!</p>
</div>
</header>
<hr />
<nav>
<!--home icon link-->
<i class="fas fa-home"></i>
Menu
Contact Us
</nav>
<hr />
<h2 class="contact-header">Contact Us</h2>
<hr />
<!--form for contact info-->
<form name="contactForm" method="post" id="contactForm" novalidate onsubmit="return validate()">
<div class="form-group col-form-label">
<label for="name">Name: </label>
<input type="text" class="form-control" id="name" placeholder="Please enter your full name.." required>
<span id="nameerror" class="hint"></span>
</div>
<div class="form-group">
<label for="email">Email: </label>
<i class="fas fa-envelope prefix"></i>
<input type="email" class="form-control" id="email" placeholder="Please enter your email address.." aria-describedby="email" required>
<span id="emailerror" class="hint"></span>
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="phone">Phone: </label>
<i class="fas fa-phone-square"></i>
<input type="tel" class="form-control" id="phone" required>
<span id="phoneerror" class="hint"></span>
</div>
<!--select menu-->
<label for="reason-select">Reason For Inquiry:</label>
<select id="select " name="reason" class="custom-select" required>
<option value="">--Please Choose an Option--</option>
<option value="catering">Catering</option>
<option value="private">Private Party</option>
<option value="feedback">Feedback</option>
<option value="other">Other</option>
</select>
<span id="selecterror" class="hint"></span>
<br />
<br />
<!--text area for additional info-->
<div class="form-group">
<label for="info">Additional Information: </label>
<textarea class="form-control" id="textarea" rows="5"></textarea>
<span id="textareaerror" class="hint"></span>
</div>
<!--radio buttons for visiting restaurant-->
<label for="radio">Have you been to the restaurant?</label>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="radio" id="no-radio" value="no">
<label class="form-check-label" for="no-radio">
No
</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="radio" id="yes-radio" value="yes">
<label class="form-check-label" for="yes-radio">
Yes
</label>
<span id="radioerror" class="hint"></span>
</div>
<br />
<!--checkboxes for contacting-->
<label for="checkboxes">Best days to contact you:</label>
<div id="checkboxlist">
<div class="form-check form-check-inline">
<input class="form-check-input" name="checkbox" type="checkbox" id="monday" value="monday">
<label class="form-check-label" for="monday">M</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" name="checkbox" type="checkbox" id="tuesday" value="tuesday">
<label class="form-check-label" for="tuesday">T</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" name="checkbox" type="checkbox" id="wednesday" value="wednesday">
<label class="form-check-label" for="wednesday">W</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" name="checkbox" type="checkbox" id="thursday" value="thursday">
<label class="form-check-label" for="thursday">Th</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" name="checkbox" type="checkbox" id="friday" value="friday">
<label class="form-check-label" for="friday">F</label>
</div>
<span id="checkboxerror" class="hint"></span>
</div>
<!--send request button-->
<div class="sendRequest" id="contact-submit">
<input type="submit" value="Send Request">
</div>
</form>
<br />
<br />
<footer>
<p>1123 Silk Way, Anchorage, AK, 99501</p>
<p>907-998-0122</p>
</footer>
</div>
<script>
document.contactForm.name.onfocus = function () {
document.getElementById('namehint').innerHTML = "(Enter full name)";
}
</script>
<!--scripts for jquery, popper, and bootstrap-->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>
<!--javascript link to external sheet-->
<script src="validate.js"></script>
<!--<script>
document.contactForm.name.onfocus = function () {
document.getElementById('namehint').innerHTML = "(Enter full name)";
}
</script>
-->
</body>
</html>
When using a submit button the default of it is to refresh or direct you to your location specified in the action attribute when defining your form html tags. If your goal is to stop this refresh, you will need to place an onClick attribute to your button that holds a function to be performed (If you know any other ways to place event listeners on DOM elements you may take that route as well I am just using this as an example), you would then would pass a variable such as event to hold the event action into the parameter. Then within the function use event.preventDefault();, this stops the refresh. After that command you can do any other validations you need to do, then trigger a refresh or new window location, whichever is your goal.
The first problem you have is you are doing:
var select = document.getElementById('select').value;
but the select is declared this way:
<select id="select " name="reason" class="custom-select" required>
it has "select " as ID, so you will get a TypeError saying you cannot read value from undefined. Its just a typo but what a typo! Just remove such trailing space:
<select id="select" name="reason" class="custom-select" required>
I think this should fix your problem. In addition, if you want to prevent the page from reloading, whether or not the form is valid, you have to prevent the default behaviour of a submit action. You can do that by calling preventDefault on the submit event, that you will need to pass to your function. Bear in mind that in this way the form will never be submitted, you will have to do it by yourself.
Pass the event to your function validate this way:
HTML
<form name="contactForm" method="post" id="contactForm" novalidate onsubmit="return validate(event)">
...
</form>
And prevent the default behaviour:
Javascript
function validate(e) {
e.preventDefault();
... // The rest of your code
}
Here is the official documentation of preventDefault
Let me know if this helps you, otherwise, tell me what went wrong.
I have a quiz with values that are added to a sum which determines the image displayed but is only showing me my raw .js file when I click submit. I am hosting it and am not sure why it is showing me this. The previous function in the file work, since the validation works and is found in that file.
HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta name="author" content="Kenneth Dunn" />
<meta name="description" content="" />
<link rel="stylesheet" href="css/random.css" type="text/css" />
</head>
<body>
<div id="page">
<div id="logo">
<h1>Overwatch</h1>
</div>
<div id="content">
<h2 align="center">Overwatch Quiz</h2>
<p>
Hi there! This quiz is dedicated to one of my favorite games Overwatch!
</p>
<form action="js/random.js" method="post" name="quiz_form" onsubmit="owchar()">
<p>
<br>
<input id='fName' name "first_name" type="text" placeholder="First Name" onblur="this.placeholder='First Name'" onfocus="this.placeholder='Use only letters'" class="validate" />
<img width="45px" height="45px"src='img/Q.png' id="fNameImg" />
</p>
<p>
<br>
<input id="last_name" name="last_name" type="text" placeholder="Last Name" onblur="this.placeholder='Last Name'" onfocus="this.placeholder='Use only Letters'" class="validate"/>
<img width="45px" height="45px" src='img/Q.png' id="last_nameImg" />
</p>
<p>
<br>
<input id="email" name="email" type="email" placeholder="Email" onblur="this.placeholder='Email'" onfocus="this.placeholder='Must contain # '" class="validate" />
<img width="45px" height="45px" src='img/Q.png' id="emailImg" />
</p>
<p>
<br>
<input id='phone' name="number" type="tel" placeholder="Phone Number" onblur="this.placeholder='Phone Number'" onfocus="this.placeholder='Must follow xxx-xxx-xxx '" class="validate" />
<img width="45px" height="45px" src='img/Q.png' id="phoneImg" />
</p>
<p>
<br>
<input id='sulley' name="sulley" type="sulley" placeholder="Sulley Email" onblur="this.placeholder='Sulley Email Address'" onfocus="this.placeholder='Must contain ~ and https:// '" class="validate"/>
<img width="45px" height="45px" src='img/Q.png' id="sulleyImg" />
</p>
<br>
<br>
<p>
<h2>Find out which Overwatch character you are most like!</h2>
<p>If you could pick what form to take in a fictional universe with magic and cool science what would you want to be?</p>
<input type="radio" name="exist" value="1">Male(Human).
<br>
<input type="radio" name="exist" value="2">Female(Human).
<br>
<input type="radio" name="exist" value="3">An Animal or something crazy.
<p>What is your preferred weapon to take on bad guys and defend yourself?</p>
<input type="radio" name="weapon" value="1">Twin Shotguns for close range.
<br>
<input type="radio" name="weapon" value="2">Twin pistols medium range.
<br>
<input type="radio" name="weapon" value="3">An electro gun that schocks enemies into submission.
<p>Which motivations most align with your own?
<p>
<input type="radio" name="idea" value="1">To become more powerful and to defeat those who would oppose me.
<br>
<input type="radio" name="idea" value="2">To explore the world and discover the unknown.
<br>
<input type="radio" name="idea" value="3">To protect my friends and those I care about.
<p>What do you look like?</p>
<input type="radio" name="look" value="1">Dark and mysterious black-hooded figure ,very edgy, like people in the Matix.
<br>
<input type="radio" name="look" value="2">Short and spunky British airforce pilot who can travel back in time.
<br>
<input type="radio" name="look" value="3">I'm a large gorilla who likes to eat bananas and peanut butter and can sheild my friends from harm.
<br>
<br>
<input type="submit" value="Submit">
<input type="reset" name="reset" id="reset" value="Reset" />
</p>
</form>
<br>
<br>
<br>
<br>
<h2 align="center" >Congratulations you got...</h2>
<div id="character" align="center" height="499" width="281" >
<img src="" id="character"/>
<br>
<br>
<br>
</div>
<div id="footer">
<h2 align="center">Created by Kenneth Dunn </h2>
</p>
</div>
</div>
</div>
<script src="js/random.js" type="text/javascript"></script>
</body>
</html>
JS
function validateData() {
console.log(this);
var letters = /^[A-Za-z]+$/;
var email = [#];
var tel = /^\d{3}-\d{3}-\d{4}$/gm;
var sulley = /[-!$%^&*()_+|~=`{}\[\]:";'<>?,.\/]/;
var imgId = this.id + 'Img';
var img = document.getElementById(imgId);
console.log(img)
var valid = false;
if (this.type == 'text') {
if (this.value.match(letters)) {
valid = true;
}
}
if (this.type == 'email') {
if (this.value.match(email)) {
valid = true;
}
}
if (this.type == 'tel') {
if (this.value.match(tel)) {
valid = true;
}
}
if (this.type == 'sulley') {
if (this.value.match(sulley)) {
valid = true;
}
}
if (valid) {
img.src = "img/check.png";
} else {
img.src = "img/redx.png";
}
}
var els = document.getElementsByClassName("validate");
for(i=0 ; i<els.length ; i++){
els[i].addEventListener("change", validateData, false);
}
function owchar(){
var sum = 0;
var w = document.forms["quiz_form"]["exist"].value;
sum+=w;
var q = document.forms["quiz_form"]["weapon"].value;
sum+=q;
var r = document.forms["quiz_form"]["idea"].value;
sum+=r;
var g = document.forms["quiz_form"]["look"].value;
sum+=g;
if (sum>1 && sum<6){
document.getElementById("character").src="img/reaper.png";
return false;
}
else if (sum>6 && sum<9){
document.getElementById("character").src="img/tracer.jpeg";
return false;
}
else {
document.getElementById("character").src="img/winston.png";
return false;
}
}
Your form is defined as:
<form action="js/random.js" method="post" name="quiz_form" onsubmit="owchar()">
The action tells the browser where to go after submission, not what js file to look in. Javascript uses a shared global scope, meaning that all JS files use the same global scope, even ones built directly into the page. Because of this Javascript awesomeness -- or weirdness (depending on your views) -- you don't need to specify where the code is that you want to run, you just have to load the code (using a <script> tag).
TL;DR;
Change this line so that it looks like the following example:
<form name="quiz_form" onsubmit="owchar()">
I used the top answer to this question to build a form that feeds into a sheet along with file upload. Now I've hit another wall.
I have categories, and sub-categories. I'd like the sub-categories to only show up IF their parent category has been selected. I just can't figure out A) where I need to put the code (on our website it's right in with the HTML), I've tried putting it in the HTML file and the Code.gs file, or B) if the code I'm using is even right.
Here's the form - the "Co-Op Category" is the parent categories, I have hidden divs for each category that would hold the 'child categories'
HTML:
<script>
// Javascript function called by "submit" button handler,
// to show results.
function updateOutput(resultHtml) {
toggle_visibility('inProgress');
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = resultHtml;
}
// From blog.movalog.com/a/javascript-toggle-visibility/
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
</script>
<div id="formDiv">
<!-- Form div will be hidden after form submission -->
<form id="myForm">
Name: <input name="name" type="text" /><br/>
Co-Op Amount: <input name="amount" type="text" /><br/>
Co-Op Split:<br />
<input type="radio" name="split" value="100%">100%<br>
<input type="radio" name="split" value="50/50">50/50<br>
<input type="radio" name="split" value="75/25">75/25<br>
Other: <input type="text" name="split" /><br />
Reason for Co-Op: <input name="reason" type="text" cols="20" rows="5" /><br />
Brand:
<select name="brand">
<option>Select Option</option>
<option>Bluebird</option>
<option>Brown</option>
<option>Ferris</option>
<option>Giant Vac</option>
<option>Honda</option>
<option>Hurricane</option>
<option>Little Wonder</option>
<option>RedMax</option>
<option>SCAG</option>
<option>Snapper Pro</option>
<option>Sno-Way</option>
<option>SnowEx</option>
<option>Wright</option>
<option>Ybravo</option>
</select><br/>
Co-Op Category:<br />
<input type="radio" name="category" id="dealer" value="Dealer Advertising">Dealer Advertising<br />
<input type="radio" name="category" id="online" value="Digital/Online Marketing">Digital/Online Advertising<br />
<input type="radio" name="category" id="meetings" value="Meetings and Schools">Meetings and Schools<br />
<input type="radio" name="category" id="advertising" value="PACE Advertising">PACE Advertising<br />
<input type="radio" name="category" id="pricing" value="Program Pricing Promotions">Program Pricing Promotions<br />
<input type="radio" name="category" id="correspondence" value="PACE-to-Dealer Correspondence">PACE-to-Dealer Correspondence<br />
Other: <input type="text" id="other" name="category" /><br />
<div class="dealer box" style="display: none;">DEALER</div>
<div class="online box" style="display: none;">ONLINE</div>
<div class="meetings box" style="display: none;">MEETINGS</div>
<div class="advertising box" style="display: none;">ADVERTISING</div>
<div class="pricing box" style="display: none;">PRICING</div>
<div class="correspondence box" style="display: none;">CORRESPONDENCE</div>
Email: <input name="email" type="text" /><br/>
Message: <textarea name="message" style="margin: 2px; height: 148px; width: 354px;"></textarea><br/>
School Schedule (Image Files Only): <input name="myFile" type="file" /><br/>
<input type="button" value="Submit"
onclick="toggle_visibility('formDiv'); toggle_visibility('inProgress');
google.script.run
.withSuccessHandler(updateOutput)
.processForm(this.parentNode)" />
</form>
</div>
<div id="inProgress" style="display: none;">
<!-- Progress starts hidden, but will be shown after form submission. -->
Uploading. Please wait...
</div>
<div id="output">
<!-- Blank div will be filled with "Thanks.html" after form submission. -->
</div>
Code.gs:
var submissionSSKey = '1zzRQwgXb0EN-gkCtpMHvMTGyhqrx1idXFXmvhj4MLsk';
var folderId = "0B2bXWWj3Z_tzTnNOSFRuVFk2bnc";
function doGet(e) {
var template = HtmlService.createTemplateFromFile('Form.html');
template.action = ScriptApp.getService().getUrl();
return template.evaluate();
}
function processForm(theForm) {
var fileBlob = theForm.myFile;
var folder = DriveApp.getFolderById(folderId);
var doc = folder.createFile(fileBlob);
// Fill in response template
var template = HtmlService.createTemplateFromFile('Thanks.html');
var name = template.name = theForm.name;
var amount = template.amount = theForm.amount;
var split = template.split = theForm.split;
var reason = template.reason = theForm.split;
var brand = template.brand = theForm.brand;
var category = template.category = theForm.category;
var message = template.message = theForm.message;
var email = template.email = theForm.email;
var fileUrl = template.fileUrl = doc.getUrl();
// Record submission in spreadsheet
var sheet = SpreadsheetApp.openById(submissionSSKey).getSheets()[0];
var lastRow = sheet.getLastRow();
var targetRange = sheet.getRange(lastRow+1, 1, 1, 9).setValues([[name,amount,split,reason,category,brand,message,email,fileUrl]]);
// Return HTML text for display in page.
return template.evaluate().getContent();
}
//Toggle Secondary Categories
function(){
$('input[type="radio"]').click(function(){
if($(this).attr("id")=="dealer"){
$(".box").not(".dealer").hide();
$(".dealer").show();
}
if($(this).attr("id")=="online"){
$(".box").not(".online").hide();
$(".online").show();
}
if($(this).attr("id")=="advertising"){
$(".box").not(".advertising").hide();
$(".advertising").show();
}
if($(this).attr("id")=="pricing"){
$(".box").not(".pricing").hide();
$(".pricing").show();
}
if($(this).attr("id")=="correspondence"){
$(".box").not(".correspondence").hide();
$(".correspondence").show();
}
if($(this).attr("id")=="meetings"){
$(".box").not(".meetings").hide();
$(".meetings").show();
}
if($(this).attr("id")=="other"){
$(".box").not(".other").hide();
$(".other").show();
}
});
};
This bit specifically is where I'm having trouble:
//Toggle Secondary Categories
function(){
$('input[type="radio"]').click(function(){
if($(this).attr("id")=="dealer"){
$(".box").not(".dealer").hide();
$(".dealer").show();
}
if($(this).attr("id")=="online"){
$(".box").not(".online").hide();
$(".online").show();
}
if($(this).attr("id")=="advertising"){
$(".box").not(".advertising").hide();
$(".advertising").show();
}
if($(this).attr("id")=="pricing"){
$(".box").not(".pricing").hide();
$(".pricing").show();
}
if($(this).attr("id")=="correspondence"){
$(".box").not(".correspondence").hide();
$(".correspondence").show();
}
if($(this).attr("id")=="meetings"){
$(".box").not(".meetings").hide();
$(".meetings").show();
}
if($(this).attr("id")=="other"){
$(".box").not(".other").hide();
$(".other").show();
}
});
};
The unexpected token is due to the function(){ line, which is invalid syntax for the jQuery document ready function. You should have:
$(function(){
$('input[type="radio"]').click(function(){
...
});
});
With that fixed, your next error will be:
Uncaught ReferenceError: $ is not defined
That's because you haven't included jQuery, which is what the $ symbol is referring to in statements like $(this). You'll want to read this for more tips about using jQuery in Google Apps Script. The short story, though: You need to add the following, adjusted for whatever version of jQuery you intend to use:
<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
Updated Form.html, which shows the appropriate <div> as you intended. It also includes the recommended doctype, html, head and body tags:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
// Javascript function called by "submit" button handler,
// to show results.
function updateOutput(resultHtml) {
toggle_visibility('inProgress');
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = resultHtml;
}
// From blog.movalog.com/a/javascript-toggle-visibility/
function toggle_visibility(id) {
var e = document.getElementById(id);
if (e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
//Toggle Secondary Categories
$(function() {
$('input[type="radio"]').click(function() {
if ($(this).attr("id") == "dealer") {
$(".box").not(".dealer").hide();
$(".dealer").show();
}
if ($(this).attr("id") == "online") {
$(".box").not(".online").hide();
$(".online").show();
}
if ($(this).attr("id") == "advertising") {
$(".box").not(".advertising").hide();
$(".advertising").show();
}
if ($(this).attr("id") == "pricing") {
$(".box").not(".pricing").hide();
$(".pricing").show();
}
if ($(this).attr("id") == "correspondence") {
$(".box").not(".correspondence").hide();
$(".correspondence").show();
}
if ($(this).attr("id") == "meetings") {
$(".box").not(".meetings").hide();
$(".meetings").show();
}
if ($(this).attr("id") == "other") {
$(".box").not(".other").hide();
$(".other").show();
}
});
});
</script>
<div id="formDiv">
<!-- Form div will be hidden after form submission -->
<form id="myForm">
Name:
<input name="name" type="text" /><br/>
Co-Op Amount: <input name="amount" type="text" /><br/>
Co-Op Split:<br />
<input type="radio" name="split" value="100%">100%<br>
<input type="radio" name="split" value="50/50">50/50<br>
<input type="radio" name="split" value="75/25">75/25<br> Other: <input type="text" name="split" /><br /> Reason for Co-Op: <input name="reason" type="text" cols="20" rows="5" /><br />
Brand:
<select name="brand">
<option>Select Option</option>
<option>Bluebird</option>
<option>Brown</option>
<option>Ferris</option>
<option>Giant Vac</option>
<option>Honda</option>
<option>Hurricane</option>
<option>Little Wonder</option>
<option>RedMax</option>
<option>SCAG</option>
<option>Snapper Pro</option>
<option>Sno-Way</option>
<option>SnowEx</option>
<option>Wright</option>
<option>Ybravo</option>
</select><br/>
Co-Op Category:<br />
<input type="radio" name="category" id="dealer" value="Dealer Advertising">Dealer Advertising<br />
<input type="radio" name="category" id="online" value="Digital/Online Marketing">Digital/Online Advertising<br />
<input type="radio" name="category" id="meetings" value="Meetings and Schools">Meetings and Schools<br />
<input type="radio" name="category" id="advertising" value="PACE Advertising">PACE Advertising<br />
<input type="radio" name="category" id="pricing" value="Program Pricing Promotions">Program Pricing Promotions<br />
<input type="radio" name="category" id="correspondence" value="PACE-to-Dealer Correspondence">PACE-to-Dealer Correspondence<br />
Other: <input type="text" id="other" name="category" /><br />
<div class="dealer box" style="display: none;">DEALER</div>
<div class="online box" style="display: none;">ONLINE</div>
<div class="meetings box" style="display: none;">MEETINGS</div>
<div class="advertising box" style="display: none;">ADVERTISING</div>
<div class="pricing box" style="display: none;">PRICING</div>
<div class="correspondence box" style="display: none;">CORRESPONDENCE</div>
Email: <input name="email" type="text" /><br/>
Message: <textarea name="message" style="margin: 2px; height: 148px; width: 354px;"></textarea><br/>
School Schedule (Image Files Only): <input name="myFile" type="file" /><br/>
<input type="button" value="Submit" onclick="toggle_visibility('formDiv'); toggle_visibility('inProgress');
google.script.run
.withSuccessHandler(updateOutput)
.processForm(this.parentNode)" />
</form>
</div>
<div id="inProgress" style="display: none;">
<!-- Progress starts hidden, but will be shown after form submission. -->
Uploading. Please wait...
</div>
<div id="output">
<!-- Blank div will be filled with "Thanks.html" after form submission. -->
</div>
</body>
</html>
I am making a questionnaire and am not brilliant with JS. I want to take the results of the radio buttons which have been marked, so either True or False, and then show them on another page. I have the questions in a form.
CODE:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styling/style.css">
<title>1</title>
</head>
<body>
<script>
function sendclick() {
var answers = [document.forms["questionarre"]["clickRule"].value,
document.forms["questionarre"]["404error"].value,
document.forms["questionarre"]["colour"].value,
document.forms["questionarre"]["H2Tag"].value,
document.forms["questionarre"]["SiteMap"].value,
document.forms["questionarre"]["heading"].value,
document.forms["questionarre"]["alttag"].value,
document.forms["questionarre"]["UseAgain"].value];
var count = 0
for (var i = 0; i<answers.length; i++) {
if (answers[i] == "") {
var temp = i+1;
alert("Please complete question "+temp);
break;
}
count++;
}
if (count == answers.length) {
var correct = [document.getElementById("correct1").checked,
document.getElementById("correct2").checked,
document.getElementById("correct3").checked,
document.getElementById("correct4").checked,
document.getElementById("correct5").checked,
document.getElementById("correct6").checked];
//window.open("YourResults.html", "_self")
}
}
/*
for (var i = 0; i<x.length; i++) {
if (x[i] == "") {
var temp = i+1;
// alert("results"+x)//window.open("results"+x);
break;}
}
}function - sendClick end
function opener() {
var text = document.getElementById('correct7').value;
var target = {
non text content : alert("correct")
};
if (text in targetNames) {
window.open(targetNames[text]);
}
}
document.getElementById('name').addEventListener('keyup', opener, false);
*/
</script>
<div id="questionarre_bg">
<form name="questionarre" action="" method="post">
<div id="Question1">
<p class="thicker">How many clicks do developers use to keep the user close to information? </p>
<input type="radio" name="clickRule" value=1>1<br>
<input type="radio" name="clickRule" value=4>4
<input type="radio" name="clickRule" id="correct1" value=3>3<br>
<input type="radio" name="clickRule" value=6>6
</div>
<div id="Question2">
<p class="thicker">How are developers using the 404 Error Page, for keep the users happy?</p>
<input type="radio" name="404error" id="correct2" value="Including links">Including links<br>
<input type="radio" name="404error" value="displaying a video">displaying a video<br>
<input type="radio" name="404error" value="playing music">playing music<br>
</div>
<div id="Question3">
<p class="thicker">Should you rely on colour alone in a website build?</p>
<input type="radio" name="colour" value="Yes">Yes<br>
<input type="radio" name="colour" id="correct3" value="No">No
</div>
<div id="Question4">
<p class="thicker">A H2 Tag is useful for?</p>
<input type="radio" name="H2Tag" id="correct4" value="The disabled autoreaders">The disabled autoreaders<br>
<input type="radio" name="H2Tag" value="Pretty webpages">Pretty webpages<br>
</div>
<div id="Question5">
<p class="thicker" >What is correct name given to page of the websites pages?</p>
<input type="radio" name="SiteMap" value="Tube Map">Tube Map
<input type="radio" name="SiteMap" id="correct5" value="Site Map">Site Map <br>
<input type="radio" name="SiteMap" value="Map">Map
<input type="radio" name="SiteMap" value="Page List">Page List
</div>
<div id="Question6">
<p class="thicker">A webpage heading should do what?</p>
<input type="radio" name="heading" id="correct6" value="Tell the user about the content in a few words">Tell the user about the content in a few words<br>
<input type="radio" name="heading" value="include meaningless text">include meaningless text<br>
<input type="radio" name="heading" value="Be short">Be short<br>
</div>
<div id="Question7">
<p class="thicker">The Alt tag is used for what....</p>
<input type="text" name="alttag" id="correct7" ><br><!--ANSWER__non text content-->
</div>
<div id="Question8">
<p class="thicker">Would you use this website again for information?</p>
<input type="radio" name="UseAgain" value="Yes">Yes<br>
<input type="radio" name="UseAgain" value="No">No<br>
<textarea rows="4" cols="50"></textarea>
</div>
</form>
<button onclick="sendclick()">send</button>
</div>
</div>
</body>
</html>
you could pass the answer through local storage
it would be something like this
//save the info on page 1
//resultArr will be the array holding all the radio results,
//you could get them by jQuery or any other method to you are comfortable with
localStorage.setItem("answers", answers);
// Retrieve the info on page 2
document.getElementById("answer1").innerHTML = localStorage.getItem("answers")[0];
you can read more about it here:
http://www.w3schools.com/html/html5_webstorage.asp
I made an application for people to fill out an application. I did some of the in form validation but now I want to ensure that when the user hits the submit button it checks to ensure that all field are filled out. I am stuck and cannot figure out the last part of this puzzle.
I believe all I need to make this work is a Application.js If someone could take a look at this and let me know what if anything I am missing. I did not include the CSS sheet or photos. Thank you for taking the time to help.
Here is the form. "Application.html"
<!DOCTYPE html>
<html>
<head>
<center><h1>AIFC Application Form</h1></center>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<title>AIFC Application</title>
<meta charset="utf-8">
<meta name="author" content="Paul Skinner">
<link rel="stylesheet" type="text/css" href="Application.css" />
<style type="text/css">
</style>
<script src="Application.js"></script>
<script src="Application_Library.js"></script>
<script type="text/javascript">
function updateTotal() {
var basePrice = 50;
var optionsPrice = 0;
var memberPrice = 0;
function checkPayment() {
if (document.getElementById('payment0').checked) {
optionsPrice += 1;
}
if (document.getElementById('payment1').checked) {
optionsPrice += 9.6;
}
} // end of checking for payment
function checkJumper() {
if (document.getElementById('jumper0').checked) {
optionsPrice += 0;
}
if (document.getElementById('jumper1').checked) {
optionsPrice += 4.4;
}
} // end of checking for Jumper
function checkMembership() {
if (document.getElementById('membership').value == 'Basic') {
memberPrice += 75;
}
if (document.getElementById('membership').value == 'Silver') {
memberPrice += 125;
}
if (document.getElementById('membership').value == 'Gold') {
memberPrice += 150;
}
} // end of check membership function
checkPayment();
checkJumper();
checkMembership();
var totalPrice = basePrice + (optionsPrice * memberPrice);
document.getElementById('optionsPrice').innerHTML = optionsPrice;
document.getElementById('memberPrice').innerHTML = "$ " + memberPrice;
document.getElementById('totalPrice').innerHTML = "$ " + totalPrice;
}
</script>
</head>
<body>
<div id="top">
<nav class="horizontalNav">
<ul>
<li>Home</li>
<li>Application</li>
<li>Who We Are</li>
<li>Our Packages</li>
</ul>
</nav></div>
<section>
<table>
<tr style="white-space:nowrap; clear:both">
<td><img src="Images/girl punching.jpg" alt="Girl Punching" style=" float:left; height:200px" /></td>
<td><img src="images/fitness.jpg" alt="Weights" style=" float:right; height:200px; width:900px" /></td>
</tr>
</table>
</section>
<form action="#" method="get" name="application" id="application" >
<div id="form">
<fieldset>
<legend>Payment Type</legend><br>
<input type="radio" name="payment" id="payment0" value="payment0" onchange="updateTotal()"> Monthly membership <br>
<input type="radio" name="payment" id="payment1" value="payment1" onchange="updateTotal()"> Yearly membership <b>Big Savings!</b> <br><br>
</fieldset>
<fieldset>
<legend>Choose a Location</legend><br>
<input type="radio" name="jumper" id="jumper0" value="jumper0" onchange="updateTotal()"> Single Gym location
<input type="radio" name="jumper" id="jumper1" value="jumper1" onchange="updateTotal()"> All Locations <br><br>
</fieldset>
<fieldset>
<legend>Membership Type</legend><br>
<select name="membership" id="membership" onchange="updateTotal()">
<option value="Basic">Basic Membership ($75)</option>
<option value="Silver">Silver Membership ($125)</option>
<option value="Gold">Gold Membership ($150)</option><br>
</select>
</fieldset>
<fieldset>
<legend>Sex</legend><br>
<input type="radio" name="sex" value="male">Male<br>
<input type="radio" name="sex" value="female">Female<br>
</fieldset>
</div>
<div id="prices">
<table>
<tr><td>Membership Application Fee</td><td id="basePrice">$50</td></tr>
<tr><td>Option factor</td><td id="optionsPrice"></td></tr>
<tr><td>Membership</td><td id="memberPrice"></td></tr>
<tr><td>Total</td><td id="totalPrice"></td></tr>
</table>
</div>
<div id="info">
<fieldset>
<legend>Personal Information</legend>
<label for="first_name">First Name:</label>
<input type="text" id="firstname" name="first" required autofocus title="First Name" placeholder="First Name" />
<span id="first_name_error"> </span><br>
<label for="last_name">Last Name:</label>
<input type="text" id="lastname" name="last" required title="Last Name" placeholder="Last Name"/>
<span id="last_name_error"> </span><br>
<label for="address">Address:</label>
<input type="text" id="address" name="address" required title="Address" placeholder="Address"/>
<span id="address_error"> </span><br>
<label for="city">City:</label>
<input type="text" id="city" name="city" required title="City" placeholder="City"/>
<span id="city_error"> </span><br>
<label for="state">State:</label>
<input type="text" id="state" maxlength="2" name="State" required title="State" placeholder="State"/>
<span id="state_error"> </span><br>
<label for="zip_code">Zip Code:</label>
<input type="text" id="zip" name="zip" required title="Zip Code" placeholder="Zip Code" pattern="\d{5}([\-]\d{4})?"/>
<span id="zip_error"> </span><br>
<label for="phone_number">Phone Number:</label>
<input type="text" id="phone" name="phone" required title="Optional Phone Number 999-999-9999" placeholder="999-999-9999" pattern="\d{3}[\-]\d{3}[\-]\d{4}"/>
<span id="phone_error"> </span><br>
<label for="date_of_birth">Date of Birth:</label>
<input type="date" name="date" required title="MM-DD-YYYY"/>
<span id="date_error"> </span><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required title="Email" placeholder="Email Address"/>
<span id="email_error"> </span>
<br>
</fieldset>
<br><br><center><input type="submit" id="submit" value="Become a Member"></center>
<br><center><input type="Reset" id="btn1" value="Reset Form"></center>
</div>
<br><br><div class="footer">
<address><center>
<b>American InterContinental Fitness Center</b> ☀
1578 Perseverance Lane ☀
Simple City, IL 60001
<br/> (630)432-1425
</address></center>
<br>
</div>
</form>
</body>
</html>
The next is the js: "Application_Library.js"
var $ = function (id) { return document.getElementById(id); }
var application = function () {
// All the different fields
this.field = [];
this.field["first_name"] = {};
this.field["last_name"] = {};
this.field["address"] = {};
this.field["city"] = {};
this.field["state"] = {};
this.field["zip"] = {};
this.field["phone"] = {};
this.field["date"] = {};
this.field["email"] = {};
// Field messages
this.field["state"].message = "Please use only a two letter State abbreviation.";
this.field["zip"].message = "Please use a 5 or 9 digit Zip Code";
this.field["phone"].message = "Please use 123-456-7890 format.";
this.field["email"].message = "Must be a vaild email address.";
// Error messages
this.field["email"].required = "Email is required";
this.field["confirmemail"].required = "Please confirm your email!";
this.field["confirmemail"].noMatch = "Emails do not Match!", "email";
this.field["first_name"].required = "First names are required.";
this.field["last_name"].required = "Last names are required.";
this.field["address"].required = "An Address is required";
this.field["city"].required = "A City is required";
this.field["state"].required = "A State is required";
this.field["state"].isState = "State invalid";
this.field["zip"].required = "A Zip code is required.";
this.field["zip"].isZip = "Zip code is invalid";
this.field["phone"].required = "A phone number is required";
this.field["phone"].isPhone = "The phone number is invalid";
this.field["date"].required = "Your date of birth is required";
}
Instead of writing your own javascript validation you can use the jQuery "form Validation Plug-in", which is an excellent tool for web pages to validate data entries at the client side using JavaScript. It's very simple to use.
Here is a sample tutorial
http://www.codeproject.com/Articles/213138/An-Example-to-Use-jQuery-Validation-Plugin
You should implement server side validation also for best security.
You can't just check data on JavaScript, you should also check it on server-side, because the client side is more accessible and user can change the JavaScript or even disable it, so the data would be invalidated.
You should write server-side validation too.
You forgot to show the Application.js file.
Also you can use HTML5 validation, without using any JavaScript:
http://www.sitepoint.com/html5-form-validation/