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()">
Related
new to stack overflow here. My question is what I might have done wrong with this quiz reset button? I have it set so that if the reset button is clicked at the end of the quiz, the quiz should return to the first question. However, the button is doing nothing. I was thinking I may have variable scope issues but I tried to accommodate for that and I still can't get the reset button to work. Thanks in advance.
HTML:
<html>
<head>
<title>Hello...</title>
</head>
<body>
<h1 id="theTitle" class="highlight summer">BATMAN QUIZ!</h1>
<div id="mainContent">
<div id="question">
</div>
<div id="choices">
<input type="radio" name="choices" /><label id="choice1" class="radios"></label></br>
<input type="radio" name="choices" /><label id="choice2" class="radios"></label></br>
<input type="radio" name="choices" /><label id="choice3" class="radios"></label></br>
<input type="submit" id="submitButton" value="Submit" /></br>
<input type="submit" class="hidden" id="nextButton" value="Next Question" />
</div>
<div class="hidden" id="answer">
</div>
</div>
</body>
</html>
CSS:
.hidden{
display:none;
}
.visible{
display:inline;
}
JavaScript:
var questionArray = [
["What is Batman's first name?", "Bruce Wayne"],
["What city does Batman live in?", "Gotham"],
["What is Commisioner Gordon's daughter's name?", "Barbara"]
];
var choicesArray = [
["Bruce Wayne", "Clark Kent", "Charles Xavier"],
["Metropolis", "Starling City", "Gotham"],
["Helen", "Barbara", "Jean"]
]
i = 0;
theQuiz(i);
function theQuiz(i) {
if (i < questionArray.length) {
var score = 0;
document.querySelector("#question").textContent = questionArray[i][0];
document.querySelector("#answer").textContent = "The correct answer is: " + questionArray[i][1];
document.querySelector("#choice1").textContent = choicesArray[i][0];
document.querySelector("#choice2").textContent = choicesArray[i][1];
document.querySelector("#choice3").textContent = choicesArray[i][2];
var answer = document.querySelector("#answer");
var submitButton = document.querySelector("#submitButton")
submitButton.addEventListener("click", showAnswer, false);
var nextButton = document.querySelector("#nextButton")
nextButton.addEventListener("click", nextQuestion, false);
function showAnswer() {
answer.classList.add("visible");
nextButton.classList.add("visible");
};
function nextQuestion() {
answer.classList.remove("visible");
nextButton.classList.remove("visible");
i++;
theQuiz(i);
};
} else {
document.body.textContent = "Game Over!";
var restartButton = document.createElement("input")
restartButton.type = "submit";
restartButton.value = "Play Again!"
document.body.appendChild(restartButton);
i=0;
theQuiz(i);
restartButton.addEventListener("click", resetGame, true);
function resetGame() {
i = 0;
theQuiz(0);
};
}
};
If you want to refresh the whole page: location.reload();
If you want to reset just where you are at on the quiz:
Wrap the whole quiz in a <form> and add this <input type='reset'> that's it.
Added and changed the following:
Required
button#fullReset and EventListeneradded
#mainContent into a <form>
<input type='reset'>added
Recommended
#choices to a <fieldset>
#theTitle inside <legend>
#answer into a <input type='hidden'>
Specification
id on <label> are useless, follow this pattern:
<label for='rad1'>Radio 1</label>
<input id='rad1' name='rads'>
Either <br> or <br/> never </br>
SNIPPET
<html>
<head>
<title>Hello...</title>
</head>
<body>
<form id="mainContent">
<fieldset id="choices">
<legend>
<h1 id="theTitle" class="highlight summer">BATMAN QUIZ!</h1>
</legend>
<input type="radio" name="choices" />
<label id="choice1" class="radios"></label>
<br>
<input type="radio" name="choices" />
<label id="choice2" class="radios"></label>
<br>
<input type="radio" name="choices" />
<label id="choice3" class="radios"></label>
<br>
<input type="submit" id="submitButton" value="Submit" />
<br>
<input type="submit" class="hidden" id="nextButton" value="Next Question" />
<input type="hidden" id="answer">
<input type='reset'>
<button id='fullReset'>Full Reset</button>
</fieldset>
</form>
<script>
var fullReset = document.getElementById('fullReset');
fullReset.addEventListener('click', function(e) {
location.reload();
}, false);
</script>
</body>
</html>
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/
I am trying to follow a tutorial on dynamic Jquery form validation but am stuck and cannot find my error. Chrome console tells me uncaught reference error: $ is not defined ( first line of my js).
this code should be validating as I type. Does anyone see an syntax error?
JS
$(function() {
/***********************************************************************************************/
/* Define some regular expressions */
/***********************************************************************************************/
var expEmail = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/,
expLettersOnly = /^[a-zA-Z ]+$/,
expLettersNumbers = /^[a-zA-Z0-9]*$/;
/***********************************************************************************************/
/* Function that checks if a field has the correct minimum length */
/***********************************************************************************************/
function validateLength( fieldValue, minLength ) {
// We remove trailing and leading whitespace
return ( $.trim( fieldValue ).length > minLength );
}
/***********************************************************************************************/
/* Validate form on typing */
/***********************************************************************************************/
$( "#rsgform1" ).on( "keyup", "input.validate-locally", function() {
validateField( $(this) );
});
/***********************************************************************************************/
/* Function that validates a field */
/***********************************************************************************************/
function validateField( field ) {
var errorText = "",
error = false,
value = field.val(),
siblings = field.siblings( ".demo-errors" );
// Test for which field is sent
switch ( field.attr( "name" ) ) {
case "firstname":
if ( !validateLength( value, 2 ) ) {
error = true;
errorText += "The name is too short!<br />";
}
if ( !expLettersOnly.test( value ) ) {
error = true;
errorText += "The name can only contain letters and spaces!";
}
break;
case "lastname":
if ( !validateLength( value, 2 ) ) {
error = true;
errorText += "The username is too short!<br />";
}
if ( !expLettersNumbers.test( value ) ) {
error = true;
errorText += "The username can only contain alphanumeric characters!";
}
break;
case "genDer":
if ( value === "0" ) {
error = true;
errorText += "Please select a gender!";
}
break;
case "email":
if ( !expEmail.test( value ) ) {
error = true;
errorText += "The email address format is invalid!";
}
break;
}
// Display the error message below the field
siblings.html( errorText );
}
});
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>RSG Contact Us</title>
</head>
<body>
<div id="contactuscall">
<form id="rsgform1" name="rsgform1" method="post" action="" novalidate>
<fieldset id="field1">
<legend id="legend1">Contact info:</legend>
<p>
<label for="firstname">First name:</label>
<input type="text" id="firstname" name="firstname" maxlength="25" class="validate-locally" />
<span class="demo-input-info">E.g John Smith, must be between 3 and 25 characters, letters and space only</span>
<span class="demo-errors"></span>
</p>
<p>
<label for="lastname">Last name:</label>
<input type="text" id="lastname" name="lastname" maxlength="25" class="validate-locally" />
<span class="demo-input-info">E.g John Smith, must be between 3 and 25 characters, letters and space only</span>
<span class="demo-errors"></span>
</p>
<p>
<label for="email">E-mail:</label>
<input type="text" id="email" name="email" maxlength="25" class="validate-locally" />
<span class="demo-input-info">E.g Jsmith#gmail.com</span>
<span class="demo-errors"></span>
</p>
<p>
<label for="cellphone">Phone:</label>
<input type="text" id="cellphone" name="cellphone" maxlength="25" class="validate-locally" />
<span class="demo-input-info">E.g 1-444-555-6666</span>
<span class="demo-errors"></span>
</p>
</fieldset>
<fieldset id="field2">
<legend id="legend2">Doggie info:</legend>
<p>
<label for="dogname">Name:</label>
<input type="text" id="dogname" name="dogname" maxlength="25" class="validate-locally" />
<span class="demo-input-info">E.g Sparky, must be between 3 and 25 characters, letters and space only</span>
<span class="demo-errors"></span>
</p>
<p>
<label for="Breed">Breed:</label>
<input type="text" id="Breed" name="Breed" maxlength="25" class="validate-locally" />
<span class="demo-input-info">E.g Beagle, Poodle, must be between 3 and 25 characters, letters and space only</span>
<span class="demo-errors"></span>
</p>
<p>
<label for="genDer">Gender:</label>
<select name="genDer" maxlength="10" class="validate-locally">
<option value="">- Select a Value-</option>
<option value="Intact Male"> Intact Male </option>
<option value="Neutered Male"> Neutered Male </option>
<option value="Intact Female"> Intact Female </option>
<option value="Neutered Female"> Neutered Female </option>
</select>
<span class="demo-errors"></span>
</p>
</fieldset>
<fieldset id="field3">
<legend id="legend3">Services Required:</legend>
<input type="checkbox" name="reasoNwalk" value="walkSale" class="textfield"/>I'm looking for a Dog Walker!
<input type="checkbox" name="reasoNfood" value="RawSale" class="textfield"/>I'm looking to purchase Raw Food!<br />
<input type="checkbox" name="reasoNgroom" value="groomSale" class="textfield"/>I'm looking for a Dog Groomer!
<input type="checkbox" name="reasoNtraining" value="trainingSale" class="textfield" />I'm looking for a Dog Trainer!
<span class="error"></span>
</fieldset>
<fieldset id="field4">
<legend id="legend4">Questions & Comments</legend>
<textarea rows="7" cols="90" id="freecomments" name="freecomments"></textarea>
</fieldset>
<!--<input id="submit" type="submit" name="submit" value="submit">-->
<input id="submit" type="submit" name="submit" value="submit">
</form>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="validate.js"></script>
</body>
</html>
Your error ddenotes that you are not included jQuery library.
Put the jquery.js before your script tag
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="js/script.js">
//your code here
</script>