Toggle sub-category divs based on radio button selection - javascript

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>

Related

Can't get button to change color based on information in the next page

I'm trying to get the background color of the button to change based on if a sessionStorage item is marked true. On the next page, the Kitchen page, when all the buttons are checked, the sessionStorage item becomes true so when you go back to the "home page",the kitchen is now marked green instead of red. This is the show completion. I think you can use jQuery but I don't really know how to use it.
Home
function loader(){
var form = document.getElementById("myForm");
//error somewhere in here
for(var i=0;i<form.length;i++){
if(sessionStorage.getItem(form.elements[i].value) == "true"){
document.getElementById(form.elements[i].value).style.backgroundColor = "green";
return true;
}else{
document.getElementById(form.elements[i].value).style.backgroundColor = "red";
return false;
}
}
}
function initial(){
if (localStorage.getItem("hasCodeRunBefore") === null) {
var form = document.forms[0];
var tot = document.forms[0].length;
var i;
for(var i = 0; i < tot ; ++i){
document.getElementById(form.elements[i].value).style.backgroundColor = "red";
}
localStorage.setItem("hasCodeRunBefore", true);
}
}
function start(){
initial();
loader();
}
Home HTML
<body onload="start()">
<header align=center>Home Screen</header>
<p align=center id="result"></p>
<script>
document.getElementById("result").innerHTML = sessionStorage.getItem("currentAddress");
</script>
<ul align=center>
<form id="myForm">
<li>
<input type="button" name="area" id="livingroom" value="Living Room" ><br><br>
<script type="text/javascript">
sessionStorage.setItem("livingroom","false");
document.getElementById("livingroom").onclick = function () {
location.href = "url";
};
</script>
</li>
<li>
<input type="button" name="area" id="kitchen" value="Kitchen"><br><br>
<script type="text/javascript">
sessionStorage.setItem("kitchen","false");
document.getElementById("kitchen").onclick = function () {
location.href = "url";
};
</script>
</li>
<li>
<input type="button" name="area" id="bathroom" value="Bathroom" ><br><br>
<script type="text/javascript">
sessionStorage.setItem("bathroom","false");
document.getElementById("bathroom").onclick = function () {
location.href = "url";
};
</script>
</li>
<li>
<input type="button" name="area" id="dining" value="Dining" ><br><br>
<script type="text/javascript">
sessionStorage.setItem("dining","false");
document.getElementById("dining").onclick = function () {
location.href = "url";
};
</script>
</li>
<li>
<input type="button" name="area" id="bedroom1" value="Bedroom 1" ><br><br>
<script type="text/javascript">
sessionStorage.setItem("bedroom1","false");
document.getElementById("bedroom1").onclick = function () {
location.href = "url";
};
</script>
</li>
</form>
</ul>
Kitchen
function checkTasks(form){
var count = 0;
for(var i=0;i<form.task.length;i++){
if(form.task[i].checked){
count++;
}
}
if(count == form.task.length){
sessionStorage.setItem("kitchen","true");
window.open("url");
}else{
alert("You have not completed all the tasks! Please check all the boxes to indicate you have completed the tasks. If there is an issue, write it in the other box.");
}
}
Kitchen HTML
<body>
<header align=center>Kitchen To Do List</header>
<form name="todolist" >
<div id="button">
<label>
<input type="checkbox" name="task" value="1" ><p>Microwave</p>
</label>
</div>
<div id="button">
<label>
<input type="checkbox" name="task" value="1"><p>Coffee Maker</p>
</label>
</div>
<div id="button">
<label>
<input type="checkbox" name="task" value="1"><p>Oven</p>
</label>
</div>
<div id="button">
<label>
<input type="checkbox" name="task" value="1"><p>Dishwasher</p>
</label>
</div>
<div id="button">
<label>
<input type="checkbox" name="task" value="1"><p>Stove Top</p>
</label>
</div>
<div id="button">
<label>
<input type="checkbox" name="task" value="1"><p>Other</p>
</label>
</div>
<textarea id="other"></textarea><br><br>
<p align=center>
<input type="submit" name="box" id="box" value="Complete" onclick="checkTasks(this.form)">
</p>
</form>
<div class="close">
<form align=center action="url" target="_self">
<input type="submit" name="back" value="Back">
</form>
</div>
Every time you load the home page you are setting the value to false with those inline scripts. Remove the sessionStorage.setItem("livingroom","false"); calls in home.html and it looks like everything will work.

dynamically add and removing div with javascript

presently stuck in situation. trying to create a form where one can dynamically add and remove div elements where necessary,so far have been a to DYNAMICALLY ADD, problem is if i try to REMOVE div,only the last created gets to delete whilst others remain(excluding the parent div)KINDLY ASSIST.
<!doctype html>
<html lang="en">
<head>
</head>
<body>
<div id="box">
<div id='div' style="background: #99CCFF; height: 100px; width:300px" >
<p>Degree Level: <select id="dropdown">
<option value="Doctorate Degree">Doctorate Degree</option>
<option value="Masters">Masters</option>
<option value="Bachelors Degree">Bachelors Degree</option>
<option value="SSCE">SSCE</option>
</select></p>
<label for="firstname">School Name</label>
<input type="text" placeholder="Your Role"">
<label for="from">From</label>
<input type="text" id="from" name="from">
<br>
<label for="to">to</label>
<input type="text" id="to" name="to">
</div>
</div>
<div>
<button id="submit1">Add new div</button>
<input type="button" value="Remove Element"
onClick="removeElement('box','div');">
</div>
</body>
<script>
var box = document.getElementById('box'),
template = box.getElementsByTagName('div'),
template = template[0];
var counter = 1;
submit1.onclick = function () {
var new_field = template.cloneNode(true);
new_field.id = new_field.id + counter++
console.log(new_field.id)
box.appendChild(new_field);
return false;
};
</script>
<script>
function removeElement(boxDiv, divDiv){
if (divDiv == boxDiv) {
alert("The parent div cannot be removed.");
}
else if (document.getElementById(divDiv)) {
var div = document.getElementById(divDiv);
var box = document.getElementById(boxDiv);
box.removeChild(div);
}
else {
alert("Child div has already been removed or does not exist.");
return false;
}
}
You are passing the string div to your remove element function which will only remove the first div.
You can find all the children elements and then remove the last child
Building on your previous code, see the snippet below
var box = document.getElementById('box'),
template = box.getElementsByTagName('div'),
template = template[0];
console.log(template);
var counter = 1;
submit1=document.getElementById("submit1");
submit1.onclick = function () {
var new_field = template.cloneNode(true);
new_field.id = new_field.id + counter++
console.log(new_field.id)
box.appendChild(new_field);
return false;
};
function removeElement(boxDiv){
var box = document.getElementById(boxDiv);
if(box.children){
console.log(box.children);
box.children[box.children.length-1].outerHTML="";
}
}
<div id="box">
<div id='div' style="background: #99CCFF; height: 100px; width:300px" >
<p>Degree Level: <select id="dropdown">
<option value="Doctorate Degree">Doctorate Degree</option>
<option value="Masters">Masters</option>
<option value="Bachelors Degree">Bachelors Degree</option>
<option value="SSCE">SSCE</option>
</select></p>
<label for="firstname">School Name</label>
<input type="text" placeholder="Your Role"">
<label for="from">From</label>
<input type="text" id="from" name="from">
<br>
<label for="to">to</label>
<input type="text" id="to" name="to">
</div>
</div>
<div>
<button id="submit1">Add new div</button>
<input type="button" value="Remove Element"
onClick="removeElement('box');">
</div>
It might be because js thinks you're only selecting the last one when doing
var div = document.getElementById(divDiv);
Try doing a loop until document.getElementById(divDiv) is undefined

My Jquery does not connect to my html

my jquery is not connecting and I cannot figure out why. I've been stumped on this for hours and I cannot figure it out.
this is my html code. The file name is exercise6.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Exercise 6</title>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="JS/exercise6.js"> </script>
</head>
<body>
<form id="email_form" name="email_form" action="exercise6.html" method="get">
<fieldset class="info">
<legend>Contact Information</legend>
<p>
<input type="text" name="Lname" id="name2" value="" required />
<label for="name2"> Last</label>
</p>
<p>
<input type="text" name="mailAddie" id="mail1" value="" required />
<label for="mail1"> Address</label>
</p>
<p>
<input type="text" name="City" id="city1" value="" />
<label for="city1"> City</label>
</p>
<p>
<input type="text" name="State" id="state1" value="" />
<label for="state1"> State</label>
</p>
<p>
<input type="number" name="Zip" id="zip1" value="" />
<label for="zip1"> Zip</label>
</p>
<p>
<input type="number" name="phoneNum" id="number" />
<label for="number"> Phone</label>
</p>
</fieldset>
<fieldset>
<legend>Sign up for our email list</legend>
<p>
<label for="email_address1"> Email Address</label>
<input type="text" name="email_address1" id="email_address1" value="" />
<span>*</span><br>
</p>
<p>
<label for="email_address2"> Confirm Email Address</label>
<input type="text" name="email_address2" id="email_address2" value="" />
<span>*</span><br>
</p>
<p>
<label for="first_name"> First</label>
<input type="text" name="first_name" id="first_name" value="" />
<span>*</span><br>
</p>
</fieldset>
<p>
<label> </label>
<input type="submit" value="Join Our List" id="join_list" >
</p>
</form>
</body>
</html>
and this is my javascript. The file name is exercise6.js and it is located in a file named JS. I do not know what I am doing wrong.
$(document).ready(function() {
$("#join_list").click(function() {
var emailAddress1 = $("#email_address1").val();
var emailAddress2 = $("#email_address2").val();
var isValid = true;
if (emailAddress1 == "") {
$("#email_address1").next().text("This field is required.");
isValid = false;
} else {
$("#email_address1").next().text("");
}
if (emailAddress2 == "") {
$("#email_address2").next().text("This field is required.");
isValid = false;
} else {
$("#email_address2").next().text("");
}
if ($("#first_name").val() == "") {
$("#first_name").next().text("This field is required.");
isValid = false
} else {
$("#first_name").next().text("");
}
if (isValid) {
$("#email_form").submit();
}
)};
)};
Can anyone help me?
The last two lines of exercise6.js both have a syntax error.
Change:
)};
)};
To:
});
});
To find this yourself next time, try using web development IDE like NetBeans with the help of right click with mouse to inspect in browser debug console, which would have even shown you where is this kind of error.
Your js code has some errors for close the function "});" try this
$(document).ready(function() {
$("#join_list").click(function() {
var emailAddress1 = $("#email_address1").val();
var emailAddress2 = $("#email_address2").val();
var isValid = true;
if (emailAddress1 == "") {
$("#email_address1").next().text("This field is required.");
isValid = false;
} else {
$("#email_address1").next().text("");
}
if (emailAddress2 == "") {
$("#email_address2").next().text("This field is required.");
isValid = false;
} else {
$("#email_address2").next().text("");
}
if ($("#first_name").val() == "") {
$("#first_name").next().text("This field is required.");
isValid = false
} else {
$("#first_name").next().text("");
}
if (isValid) {
$("#email_form").submit();
}
});
});

Resetting a quiz with reset button

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>

How do I take the values of a Radio Button to a new page, after i have checked if they are correct?

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

Categories

Resources