I am new to creating complex code on HTML and J.script, I have been working with server hardware maintenance and resolving OS issues for 4 years. I wanted to create a web based troubleshooting decision tree which I could host online that would help anyone in need on performing logical troubleshooting on servers. I was able to get an example code from twoseven.co.nz, (courtesy Dan) which matched my requirement but I think I am doing something wrong.
I am able to get output correctly till question_1_2_2,
Though It doesn't go ahead and doesn't show output for step3 option21
I have added the code, it would be great if someone could point me in the right direction. Thanks in advance.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Decision Tree - Server Logical Troubleshooting</title>
<script type='text/javascript' src='https://code.jquery.com/jquery-1.5.js'></script>
<style type='text/css'>
fieldset {margin:10px 0;}
.hide {display:none;}
</style>
<!--
<link rel="stylesheet" type="text/css" href="/css/normalize.css">
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<!-- commented out external stylesheets due to relative URLs.
-->
<script type='text/javascript'>//<![CDATA[
var base = {
productFilterSetup: function() {
$('.productFilter').each(
function() {
var tmp = new base.filterGroup(this);
tmp.setup();
});
},
filterGroup: function(filter_group) {
var me = this;
me.target_element = filter_group;
me.active_element_index = 0;
me.setup = function() {
$(filter_group).find('input[type=radio]').bind('click', function() {
me.update(this);
});
};
me.update = function(target_radio) {
var fieldsets = $(me.target_element).find('fieldset'),
len = fieldsets.length,
i = 0,
j = 0,
radios,
radios_len,
options = [],
options_buffer = '',
num_of_steps = 0;
for (i = 1; i <= num_of_steps + 1; i += 1) {
if ($('fieldset.step' + i).length > 0) {
num_of_steps += 1;
}
}
for (i = 0; i < num_of_steps; i += 1) {
if ($(target_radio).parents('fieldset.step' + (i + 1)).length > 0) {
for (j = i; j < num_of_steps; j += 1) {
$('fieldset.step' + (j + 2) + ' input[type=radio]').attr('checked', false);
}
}
}
for (i = 0; i < len; i += 1) {
radios = $(fieldsets[i]).find('input[type=radio]');
radios_len = radios.length;
for (j = 0; j < radios_len; j += 1) {
if ($(radios[j]).is(':checked')) {
options.push(j + 1);
}
}
}
fieldsets.addClass('hide');
$('fieldset.option0').removeClass('hide');
for (i = 0; i < options.length; i += 1) {
options_buffer += options[i];
$('fieldset.option' + options_buffer).removeClass('hide');
}
};
}
};
$(
function() {
base.productFilterSetup();
});
//]]>
</script>
</head>
<body>
<h4>No POWER</h4>
<form action="#" id="unique_id" class="productFilter">
<fieldset class="step1 option0">
<legend>Is the Server in a Rack?</legend>
<p>
<input id="question_1" name="group_1" type="radio" />
<label for="question_1">Yes!</label>
</p>
<p>
<input id="question_2" name="group_1" type="radio"/>
<label for="question_2">No.</label>
</p>
</fieldset>
<fieldset class="hide step2 option1">
<legend>Are other servers in the Rack receiving Power?</legend>
<p>
<input id="question_1_1" name="group_2" type="radio" />
<label for="question_1_1">Yes</label>
</p>
<p>
<input id="question_1_2" name="group_2" type="radio" />
<label for="question_1_2">No</label>
</p>
</fieldset>
<fieldset class="hide step2 option2">
<legend>Try Different Wall Sockets, Still No Power</legend>
<p>
<input id="question_2_1" name="group_3" type="radio" />
<label for="question_2_1">Yes</label>
</p>
<p>
<input id="question_2_2" name="group_3" type="radio" />
<label for="question_2_2">No</label>
</p>
</fieldset>
<fieldset class="hide step3 option11">
<legend>The Rack Power is fine, Try different power sockets in Rack, Still No Power?</legend>
<p>
<input id="question_1_1_1" name="group_4" type="radio"/>
<label for="question_1_1_1">Yes</label>
</p>
<p>
<input id="question_1_1_2" name="group_4" type="radio"/>
<label for="question_1_1_2">No</label>
</p>
</fieldset>
<fieldset class="hide step3 option12">
<legend>Check Rack Power (PDU) and Main Power and UPS</legend>
<p>
<input id="question_1_2_1" name="group_5" type="radio"/>
<label for="question_1_2_1">Yes</label>
</p>
<p>
<input id="question_1_2_2" name="group_5" type="radio" />
<label for="question_1_2_2">No</label>
</p>
</fieldset>
<fieldset class="hide step3 option21">
<legend>Reseat the power cables on the server PSU ,Still No Power</legend>
<p>
<input id="question_2_1_1" name="group_6" type="radio" />
<label for="question_2_1_1">Yes</label>
</p>
<p>
<input id="question_2_1_2" name="group_6" type="radio" />
<label for="question_2_1_2">No</label>
</p>
</fieldset>
<fieldset class="hide step3 option22">
<legend>Its an Issue with the wall socket</legend>
<p>
<input id="question_2_2_1" name="group_7" type="radio" />
<label for="question_2_2_1">Resolved</label>
</p>
<p>
<input id="question_2_2_2" name="group_7" type="radio" />
<label for="question_2_2_2">No</label>
</p>
</fieldset>
</form>
<p>Troubleshooting Flowchart</p>
<a title="A button." href="#" class="buttonGreen"><span></span></a>
</body>
</html>
Related
This question already has answers here:
How can I get form data with JavaScript/jQuery?
(31 answers)
Closed last year.
I'm new to coding and learning HTML as well as JavaScript. I wrote a set of radio buttons in HTML so that you could toggle an option and click the submit button, and it would use JS to display the option you chose below. The code works fine, however:
The code is quite clunky, I'm positive there must be a much more effective way of writing this code.
I didn't use the form tag, should I? I'm still not entirely sure what form does other than I know it's used to collect data somehow
var x;
function displayText() {
if (document.getElementById("lsd").checked === true) {
x = document.getElementById("lsd").value;
document.getElementById("output").innerHTML = x;
} else if (document.getElementById("shrooms").checked === true) {
x = document.getElementById("shrooms").value;
document.getElementById("output").innerHTML = x;
} else if (document.getElementById("dmt").checked === true) {
x = document.getElementById("dmt").value;
document.getElementById("output").innerHTML = x;
} else if (document.getElementById("peyote").checked === true) {
x = document.getElementById("peyote").value;
document.getElementById("output").innerHTML = x;
} else if (document.getElementById("toad").checked === true) {
x = document.getElementById("toad").value;
document.getElementById("output").innerHTML = x;
}
}
<p>What's your preferred psychedelic substance?</p>
<input type="radio" id="lsd" name="drugs" value="lsd">
<label for="lsd">LSD</label>
<br>
<input type="radio" id="shrooms" name="drugs" value="shrooms">
<label for="shrooms">Magic Mushrooms/psilocybin</label>
<br>
<input type="radio" id="dmt" name="drugs" value="dmt">
<label for="dmt">DMT</label>
<br>
<input type="radio" id="peyote" name="drugs" value="peyote">
<label for="peyote">Peyote</label>
<br>
<input type="radio" id="toad" name="drugs" value="toad">
<label for="toad">The Toad/5-MeO-DMT</label>
<br>
<button onclick="displayText()">Submit!</button>
<p>
User's favorite drug is: <span id="output"></span>
</p>
A more powerful selector can select the element you want without manually checking each
function displayText() {
const selected = document.querySelector("[name='drugs']:checked");
const value = selected ? selected.value :null;
document.getElementById("output").innerText = value;
}
<p>What's your preferred psychedelic substance?</p>
<input type="radio" id="lsd" name="drugs" value="lsd">
<label for="lsd">LSD</label>
<br>
<input type="radio" id="shrooms" name="drugs" value="shrooms">
<label for="shrooms">Magic Mushrooms/psilocybin</label>
<br>
<input type="radio" id="dmt" name="drugs" value="dmt">
<label for="dmt">DMT</label>
<br>
<input type="radio" id="peyote" name="drugs" value="peyote">
<label for="peyote">Peyote</label>
<br>
<input type="radio" id="toad" name="drugs" value="toad">
<label for="toad">The Toad/5-MeO-DMT</label>
<br>
<button onclick="displayText()">Submit!</button>
<p>
User's favorite drug is: <span id="output"></span>
</p>
You can simplify it like this:
You can paste it directly in HTML file and test.
I would not recommend this for prod but for learning purposes it is good.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
name="viewport">
<meta content="ie=edge" http-equiv="X-UA-Compatible">
<title>Document</title>
</head>
<body>
<p>What's your preferred psychedelic substance?</p>
<form id="form">
</form>
<button onclick="displayText()">Submit!</button>
<p>
User's favorite drug is: <span id="output"></span>
</p>
</body>
<script>
const drugs = {
"lsd": "LSD",
"shrooms": "Magic Mushrooms/psilocybin",
"dmt": "DMT",
"peyote": "Peyote",
"toad": "The Toad/5-MeO-DMT"
};
const form = document.getElementById("form");
for (const key in drugs) {
form.innerHTML += `
<label style="display: block" for="lsd">
<input type="radio" id="${key}" name="drugs" value="${key}">
${drugs[key]}
</label>`;
}
function displayText() {
const drugs = document.getElementsByName("drugs");
for (let i = 0; i < drugs.length; i++) {
if (drugs[i].checked) {
document.getElementById("output").innerHTML = drugs[i].value;
}
}
}
</script>
</html>
I'm trying to validate the radio buttons so that an error pops up when it's not checked.
However the error won't disappear unless I select an option from the Question 2 set and nothing from Question 1.
I'm trying to have both messages pop up for both questions if unchecked and and individually disappear when something is selected for that question
//Javascript
var answers = ["A","C"],
total = answers.length;
function getCheckedValue(radioName)
{
var radios = document.getElementsByName(radioName);
var errorSpan = document.getElementById("choice_error");
var isChecked = false;
errorSpan.innerHTML = "";
for (var y = 0; y < radios.length; y++)
{
if(radios[y].checked)
{
isChecked = true;
return radios[y].value
}
else if(!radios[y].checked)
{
isChecked = false;
errorSpan.innerHTML = "Please select a choice.";
}
}
return isChecked;
}
function getScore()
{
var score = 0;
for (var i = 0; i < total; i++)
{
document.getElementById("flag"+i).innerHTML = "";
if(getCheckedValue("choice"+i) == answers[i])
{
score += 1;
document.getElementById("flag"+i).innerHTML = "Your answer is correct.";
}
else if(getCheckedValue("choice"+i) != answers[i])
{
document.getElementById("flag"+i).innerHTML = "Your answer is incorrect.";
}
}
return score;
}
function returnScore()
{
var x = document.getElementById("myText").value;
document.getElementById("results").innerHTML = x + ", your score is " + getScore() + "/" + total;
}
<!--HTML -->
<!DOCTYPE html>
<html lang="en">
<head>
<title>Disney Quiz</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="images/favicon.ico">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/main.css">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<script src="scripts/quiz.js"></script>
</head>
<body>
<header><h1>Disney Quiz</h1></header>
<main>
<p>Click on the correct answer for each question and submit your results.</p>
<form>
<fieldset>
<legend>Trivia Questions</legend>
<label> Enter your Name</label> <input type="text" id="myText" name="fieldName" placeholder="First Last"value=""><br>
<section id="radio1">
<p> Question 1) What was Walt Disney's first character he created? <span id="choice_error"></span></p>
<input type="radio" name="choice0" value="A">Oswald the Lucky Rabbit<br>
<input type="radio" name="choice0" value="B">Donald Duck<br>
<input type="radio" name="choice0" value="C">Mickey Mouse<br>
<input type="radio" name="choice0" value="D">Goofy<br>
<p id="flag0"></p>
</section>
<section id="radio2">
<p> Question 2) Snow White was the first ____ to ever be produced successfully. <span id="choice_error"></span></p></p>
<input type="radio" name="choice1" value="A">Movie<br>
<input type="radio" name="choice1" value="B">Live-Action<br>
<input type="radio" name="choice1" value="C">Cel-animated Film<br>
<input type="radio" name="choice1" value="D">Cartoon<br>
<p id="flag1"><p>
</section>
<br>
<input type="button" onclick="returnScore()" value="Show Results">
<input type="button" onclick="window.location.href = 'index.html';" value="Review">
<p id="results"></p>
</fieldset>
</form>
</main>
<aside>
</aside>
<footer> <p align="center"> Project 4 - Fall 2018 </p> </footer>
</body>
</html>
fastest method:
HTML:
<span id="choice_error_choice0"></span>
<!-- ... -->
<span id="choice_error_choice1"></span>
JS:
function getCheckedValue(radioName)
{
let isChecked = true;
let exist = document.querySelector(`input[name='${radioName}']:checked`);
let choice_error = document.getElementById('choice_error_'+radioName);
choice_error.innerHTML = "";
if (exist == null)
{
isChecked = false;
choice_error.innerHTML = "Please select a choice.";
}
return isChecked;
}
In your code both error spans have the same ID "choice_error". No two html elements should have the same id, as then the browser won't be able to differentiate them.
If you want to access both error span elements, you can give each of them a ccs class "choice_error" and call the method document.getElementsByClassName().
Also you need to clear the error span inside the loop
function getCheckedValue(radioName)
{
var radios = document.getElementsByName(radioName);
var errorSpans = document.getElementsByClassName("choise_error");
var isChecked = false;
for (var y = 0; y < radios.length; y++)
{
errorSpans[y].innerHTML= ""; // clear the span
if(radios[y].checked)
{
isChecked = true;
return radios[y].value
}
else if(!radios[y].checked)
{
isChecked = false;
errorSpans[y].innerHTML = "Please select a choice."; // error message
}
}
return isChecked;
}
I've tidied a couple of things up. Using label for a start.
The main difference is I now use a parent question id to group our answers and change to class for choice_error.
Then I've use document.querySelector to find the checked answer and set the child error messages display style.
//Javascript
var answers = ["A", "C"],
total = answers.length;
function getAnswer(QuestionId) {
//Get the selected answer radio button
var answer = document.querySelector("#" + QuestionId + " input[type=radio]:checked");
//It there isn't one
if (answer === null) {
//show the error mesage
document.querySelector("#" + QuestionId + " .choice_error").style.display = "inline";
} else {
//Otherwise hide the message
document.querySelector("#" + QuestionId + " .choice_error").style.display = "";
//And set the answer value
answer = answer.value;
}
return answer;
}
function getScore() {
var score = 0;
for (var i = 0; i < total; i++) {
document.getElementById("flag" + i).innerHTML = "";
if (getAnswer("radio" + (i + 1)) == answers[i]) {
score += 1;
document.getElementById("flag" + i).innerHTML = "Your answer is correct.";
}
/*No need to check again, it either matches or doesn't*/
else {
document.getElementById("flag" + i).innerHTML = "Your answer is incorrect.";
}
}
return score;
}
function returnScore() {
var x = document.getElementById("myText").value;
document.getElementById("results").innerHTML = x + ", your score is " + getScore() + "/" + total;
}
.questions label {
display: block;
}
.choice_error {
color: red;
display: none;
}
<!--HTML -->
<!DOCTYPE html>
<html lang="en">
<head>
<title>Disney Quiz</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="images/favicon.ico">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/main.css">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<script src="scripts/quiz.js"></script>
</head>
<body>
<header>
<h1>Disney Quiz</h1>
</header>
<main>
<p>Click on the correct answer for each question and submit your results.</p>
<form>
<fieldset>
<legend>Trivia Questions</legend>
<label> Enter your Name</label> <input type="text" id="myText" name="fieldName" placeholder="First Last" value=""><br>
<section id="radio1" class="questions">
<p> Question 1) What was Walt Disney's first character he created? <span class="choice_error">Please select a choice</span></p>
<label><input type="radio" name="choice0" value="A">Oswald the Lucky Rabbit</label>
<label><input type="radio" name="choice0" value="B">Donald Duck</label>
<label><input type="radio" name="choice0" value="C">Mickey Mouse</label>
<label><input type="radio" name="choice0" value="D">Goofy</label>
<p id="flag0"></p>
</section>
<section id="radio2" class="questions">
<p> Question 2) Snow White was the first ____ to ever be produced successfully. <span class="choice_error">Please select a choice</span></p>
<label><input type="radio" name="choice1" value="A">Movie</label>
<label><input type="radio" name="choice1" value="B">Live-Action</label>
<label><input type="radio" name="choice1" value="C">Cel-animated Film</label>
<label><input type="radio" name="choice1" value="D">Cartoon</label>
<p id="flag1">
<p>
</section>
<br>
<input type="button" onclick="returnScore()" value="Show Results">
<input type="button" onclick="window.location.href = 'index.html';" value="Review">
<p id="results"></p>
</fieldset>
</form>
</main>
<aside>
</aside>
<footer>
<p align="center"> Project 4 - Fall 2018 </p>
</footer>
</body>
</html>
We could refactor this some more, let one method handle manipulating the question related actions.
//Javascript
var answers = ["A", "C"],
total = answers.length;
function checkAnswer(QuestionId, Answer) {
var isCorrect = false;
var questionElement = document.getElementById(QuestionId);
//Get the selected answer radio button
var answerElement = questionElement.querySelector("input[type=radio]:checked");
//It there isn't one
if (answerElement === null) {
//show the error mesage
questionElement.querySelector(".choice_error").style.display = "inline";
questionElement.querySelector("[id^=flag]").innerHTML = "";
} else {
//Otherwise hide the message
questionElement.querySelector(".choice_error").style.display = "";
//And chcek answer
isCorrect = Answer == answerElement.value;
questionElement.querySelector("[id^=flag]").innerHTML = "Your answer is " + (isCorrect ? "correct" : "incorrect");
}
return isCorrect;
}
function getScore() {
var score = 0;
for (var i = 0; i < total; i++) {
if(checkAnswer("radio" + (i + 1), answers[i])) {
score++;}
}
return score;
}
function returnScore() {
var x = document.getElementById("myText").value;
document.getElementById("results").innerHTML = x + ", your score is " + getScore() + "/" + total;
}
.questions label {
display: block;
}
.choice_error {
color: red;
display: none;
}
<!--HTML -->
<!DOCTYPE html>
<html lang="en">
<head>
<title>Disney Quiz</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="images/favicon.ico">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/main.css">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<script src="scripts/quiz.js"></script>
</head>
<body>
<header>
<h1>Disney Quiz</h1>
</header>
<main>
<p>Click on the correct answer for each question and submit your results.</p>
<form>
<fieldset>
<legend>Trivia Questions</legend>
<label> Enter your Name</label> <input type="text" id="myText" name="fieldName" placeholder="First Last" value=""><br>
<section id="radio1" class="questions">
<p> Question 1) What was Walt Disney's first character he created? <span class="choice_error">Please select a choice</span></p>
<label><input type="radio" name="choice0" value="A">Oswald the Lucky Rabbit</label>
<label><input type="radio" name="choice0" value="B">Donald Duck</label>
<label><input type="radio" name="choice0" value="C">Mickey Mouse</label>
<label><input type="radio" name="choice0" value="D">Goofy</label>
<p id="flag0"></p>
</section>
<section id="radio2" class="questions">
<p> Question 2) Snow White was the first ____ to ever be produced successfully. <span class="choice_error">Please select a choice</span></p>
<label><input type="radio" name="choice1" value="A">Movie</label>
<label><input type="radio" name="choice1" value="B">Live-Action</label>
<label><input type="radio" name="choice1" value="C">Cel-animated Film</label>
<label><input type="radio" name="choice1" value="D">Cartoon</label>
<p id="flag1">
<p>
</section>
<br>
<input type="button" onclick="returnScore()" value="Show Results">
<input type="button" onclick="window.location.href = 'index.html';" value="Review">
<p id="results"></p>
</fieldset>
</form>
</main>
<aside>
</aside>
<footer>
<p align="center"> Project 4 - Fall 2018 </p>
</footer>
</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 got the following Javascript code that works properly in Mozilla Firefox but it doesn't in Google Chrome. Any ideea why it will do that?
totalBMI in Chrome even if the value is 45(checking all the last buttons will give you the value 45 which is bigger then 26 so the result should be setting the hRisk div to display:-inline instead of display:none, as the function changeCss() does.) it still consider it to be 0, cause it displays the low risk message. In Firefox, it always displays the right answer.
Javascript code :
function CalculateValue() {
var age = +getAgeValue('age'),
bmi = +getBmiValue('bmi'),
fami = +getFamValue('fam'),
diet = +getDietValue('diet'),
totalBMI = age + bmi + fami + diet;
totalBMI = parseFloat(totalBMI);
alert(totalBMI);
if (totalBMI > 26) {
function changeCSS() {
document.getElementById("btn").onclick = function() {
var hMessage = document.getElementById("hRisk");
hMessage.style.display = 'inline';
/*var newSpan = document.createElement("span");
var newSpanText = document.createTextNode("Your main factors risk are " );
newSpan.appendChild(newSpanText);
var pElem = document.getElementById("space");
pElem.appendChild(newSpan); */
}
}
changeCSS();
} else if (totalBMI > 16 ) {
function changeCSS() {
document.getElementById("btn").onclick = function() {
var mMessage = document.getElementById("mRisk");
mMessage.style.display = 'inline';
}
}
changeCSS();
} else {
function changeCSS() {
document.getElementById("btn").onclick = function() {
var lMessage = document.getElementById("lRisk");
lMessage.style.display = 'inline';
}
}
changeCSS();
}
}
function getAgeValue()
{
for (var i = 0; i < document.getElementsByName('age').length; i++)
{
if (document.getElementsByName('age')[i].checked)
{
return document.getElementsByName('age')[i].value;
}
}
}
function getBmiValue()
{
for (var i = 0; i < document.getElementsByName('bmi').length; i++)
{
if (document.getElementsByName('bmi')[i].checked)
{
return document.getElementsByName('bmi')[i].value;
}
}
}
function getFamValue()
{
for (var i = 0; i < document.getElementsByName('fam').length; i++)
{
if (document.getElementsByName('fam')[i].checked)
{
return document.getElementsByName('fam')[i].value;
}
}
}
function getDietValue()
{
for (var i = 0; i < document.getElementsByName('diet').length; i++)
{
if (document.getElementsByName('diet')[i].checked)
{
return document.getElementsByName('diet')[i].value;
}
}
}
HTML code:
<script src="jsbmi4.js"></script>
<title>Java</title>
<body>
<form method="post" action="process.php" id="radioForm">
<fieldset>
<div>
<label for="age" class="lClass"> <span class="span1"> How old are you? </span>
<input type="radio" id="age1" name="age" value="0">0-25
<input type="radio" id="age1" name="age" value="5">26-40
<input type="radio" id="age1" name="age" value="8">41-60
<input type="radio" id="age1" name="age" value="10">60+
</label>
</div>
<div>
<label for="bmi"> <span class="span1"> What is your BMI? </span>
<input type="radio" id="bmi1" name="bmi" value="0">0-25
<input type="radio" id="bmi1" name="bmi" value="0">26-30
<input type="radio" id="bmi1" name="bmi" value="9">31-35
<input type="radio" id="bmi1" name="bmi" value="10">35+
</label>
</div>
<div>
<label for="fam"> <span class="span1"> Does anybody in your family have diabetes? </span>
<input type="radio" id="fam1" name="fam" value="0">No
<input type="radio" id="fam1" name="fam" value="7">Grandparent
<input type="radio" id="fam1" name="fam" value="15">Sibling
<input type="radio" id="fam1" name="fam" value="15">Parent
</label>
</div>
<div>
<label for="diet"> <span class="span1"> How would you describe your diet? </span>
<input type="radio" id="diet1" name="diet" value="0">Low sugar
<input type="radio" id="diet1" name="diet" value="0">Normal sugar
<input type="radio" id="diet1" name="diet" value="7">Quite high sugar
<input type="radio" id="diet1" name="diet" value="10">High sugar
</label>
</div>
<div class="button">
<input id="btn" type="button" value="Calculate" onclick="CalculateValue()">
<!-- <input id="submit" type"submit" value="submit"> -->
</div>
</fieldset>
</form>
<div id="lRisk">
<h2> Your Result </h2>
<p> Your results show that you currently have a low risk of developing diabetes. However, it is important that you maintain a healty lifestyle in terms of diet and exercise. </p>
</div>
<div id="mRisk">
<h2> Your Result </h2>
<p> Your results show that you currently have a medium risk of developing diabetes. For more information on your risk factors, and what to do about them, please visit our diabetes advice website at http://www.zha.org.zd. </p>
</div>
<div id="hRisk">
<h2> Your Result </h2>
<p>Your results show that you currently have a HIGH risk of developing diabetes.<span id="space"></span> We advice that you contact the Health Authority to discuss your risk factors as soon as you can. Please fill in our contact form and a member of the Health Authority Diabetes Team will be in contact with you. </p>
</div>
</body>
Only modification that I had to do is delete the function changeCSS() and just add what was inside in the if statement.
Thanks Fuximus Foe.
JSCode is here.
function getAgeValue()
{
for (var i = 0; i < document.getElementsByName('age').length; i++)
{
if (document.getElementsByName('age')[i].checked)
{
return document.getElementsByName('age')[i].value;
}
}
}
function getBmiValue()
{
for (var i = 0; i < document.getElementsByName('bmi').length; i++)
{
if (document.getElementsByName('bmi')[i].checked)
{
return document.getElementsByName('bmi')[i].value;
}
}
}
function getFamValue()
{
for (var i = 0; i < document.getElementsByName('fam').length; i++)
{
if (document.getElementsByName('fam')[i].checked)
{
return document.getElementsByName('fam')[i].value;
}
}
}
function getDietValue()
{
for (var i = 0; i < document.getElementsByName('diet').length; i++)
{
if (document.getElementsByName('diet')[i].checked)
{
return document.getElementsByName('diet')[i].value;
}
}
}
function CalculateValue() {
var age = +getAgeValue('age'),
bmi = +getBmiValue('bmi'),
fami = +getFamValue('fam'),
diet = +getDietValue('diet'),
totalBMI = age + bmi + fami + diet;
totalBMI = parseFloat(totalBMI);
alert(totalBMI);
if (totalBMI > 26) {
document.getElementById("btn").onclick = function() {
var hMessage = document.getElementById("hRisk");
hMessage.style.display = 'inline';
/*var newSpan = document.createElement("span");
var newSpanText = document.createTextNode("Your main factors risk are " );
newSpan.appendChild(newSpanText);
var pElem = document.getElementById("space");
pElem.appendChild(newSpan); */
}
} else if (totalBMI > 16 ) {
document.getElementById("btn").onclick = function() {
var mMessage = document.getElementById("mRisk");
mMessage.style.display = 'inline';
}
} else {
document.getElementById("btn").onclick = function() {
var lMessage = document.getElementById("lRisk");
lMessage.style.display = 'inline';
}
}
}
You have not closed any input tags consider using <input ... /> self closing tags. You have misplaced closing </label> tags.
You shouldn't redeclare a function just to use on the next line.
Not sure, why you're binding to onclick event when you already have the answer, that makes it work only when the user hits the calculate button twice.
After fiddling around with this, removing the the changeCSS functions and just executing their code straight away fixes the problem. This is because in Chrome is grabbing the first definition of the function regardless whether the cursor reaches it or not, thus executing only the first changeCSS function on all three cases; firefox reads the correct definition.
JAVASCRIPT:
function CalculateValue() {
var totalBMI = 0+parseInt(getAgeValue('age'))
+parseInt(getBmiValue('bmi'))
+parseInt(getFamValue('fam'))
+parseInt(getDietValue('diet'));
alert(totalBMI);
if (totalBMI > 26) {
//function changeCSS(){
//document.getElementById("btn").onclick = function () {
var hMessage = document.getElementById("hRisk");
hMessage.style.display = 'block';
/*var newSpan = document.createElement("span");
var newSpanText = document.createTextNode("Your main factors risk are " );
newSpan.appendChild(newSpanText);
var pElem = document.getElementById("space");
pElem.appendChild(newSpan); */
//}
//}
//changeCSS();
} else if (totalBMI > 16) {
//function changeCSS(){
//document.getElementById("btn").onclick = function () {
var mMessage = document.getElementById("mRisk");
mMessage.style.display = 'block';
//}
//}
//changeCSS();
} else {
//function changeCSS(){
//document.getElementById("btn").onclick = function () {
var lMessage = document.getElementById("lRisk");
lMessage.style.display = 'block';
//}
//}
//changeCSS();
}
}
function getAgeValue() {
for (var i = 0; i < document.getElementsByName('age').length; i++) {
if (document.getElementsByName('age')[i].checked) {
return document.getElementsByName('age')[i].value;
}
}
return 0;
}
function getBmiValue() {
for (var i = 0; i < document.getElementsByName('bmi').length; i++) {
if (document.getElementsByName('bmi')[i].checked) {
return document.getElementsByName('bmi')[i].value;
}
}
return 0;
}
function getFamValue() {
for (var i = 0; i < document.getElementsByName('fam').length; i++) {
if (document.getElementsByName('fam')[i].checked) {
return document.getElementsByName('fam')[i].value;
}
}
return 0;
}
function getDietValue() {
for (var i = 0; i < document.getElementsByName('diet').length; i++) {
if (document.getElementsByName('diet')[i].checked) {
return document.getElementsByName('diet')[i].value;
}
}
return 0;
}
HTML:
<body>
<form method="post" action="process.php" id="radioForm">
<fieldset>
<div>
<label for="age" class="lClass"><span class="span1"> How old are you?</span></label>
<input type="radio" id="age1" name="age" value="0"/>0-25
<input type="radio" id="age1" name="age" value="5"/>26-40
<input type="radio" id="age1" name="age" value="8"/>41-60
<input type="radio" id="age1" name="age" value="10"/>60+
</div>
<div>
<label for="bmi"> <span class="span1"> What is your BMI? </span></label>
<input type="radio" id="bmi1" name="bmi" value="0"/>0-25
<input type="radio" id="bmi1" name="bmi" value="0"/>26-30
<input type="radio" id="bmi1" name="bmi" value="9"/>31-35
<input type="radio" id="bmi1" name="bmi" value="10"/>35+
</div>
<div>
<label for="fam"> <span class="span1"> Does anybody in your family have diabetes?</span></label>
<input type="radio" id="fam1" name="fam" value="0"/>No
<input type="radio" id="fam1" name="fam" value="7"/>Grandparent
<input type="radio" id="fam1" name="fam" value="15"/>Sibling
<input type="radio" id="fam1" name="fam" value="15"/>Parent
</div>
<div>
<label for="diet"> <span class="span1"> How would you describe your diet? </span></label>
<input type="radio" id="diet1" name="diet" value="0"/>Low sugar
<input type="radio" id="diet1" name="diet" value="0"/>Normal sugar
<input type="radio" id="diet1" name="diet" value="7"/>Quite high sugar
<input type="radio" id="diet1" name="diet" value="10"/>High sugar
</div>
<div class="button">
<input id="btn" type="button" value="Calculate" onclick="CalculateValue()"/>
<!-- <input id="submit" type"submit" value="submit"> -->
</div>
</fieldset>
</form>
<div id="lRisk" style="display:none;">
<h2> Your Result </h2>
<p> Your results show that you currently have a low risk of developing diabetes. However, it is important that you maintain a healty lifestyle in terms of diet and exercise. </p>
</div>
<div id="mRisk" style="display:none;">
<h2> Your Result </h2>
<p> Your results show that you currently have a medium risk of developing diabetes. For more information on your risk factors, and what to do about them, please visit our diabetes advice website at http://www.zha.org.zd. </p>
</div>
<div id="hRisk" style="display:none;">
<h2> Your Result </h2>
<p>Your results show that you currently have a HIGH risk of developing diabetes.<span id="space"></span> We advice that you contact the Health Authority to discuss your risk factors as soon as you can. Please fill in our contact form and a member of the Health Authority Diabetes Team will be in contact with you. </p>
</div>
</body>
and the JSFiddle: http://jsfiddle.net/kWyx8/
I am trying to build a very simple dot chasing game as a homework assignment, and I cannot figure out how to carry over the difficulty selection from the index page to the actual game page.
Index Page
<form id="difficulty" name="difficulty" action="game.html">
<input type="radio" name="diff" id="easyDiff" value="easy">
<label for="easyDiff">Easy</label>
<input type="radio" name="diff" id="medDiff" value="medium" checked="checked">
<label for="medDiff">Medium</label>
<input type="radio" name="diff" id="hardDiff" value="hard">
<label for="hardDiff">Hard</label>
<input type="submit" value="Start Game!" onClick="setDifficulty()"/>
</form>
Game Page
<html>
<head>
<title>DotSmasher</title>
<link rel="stylesheet" href="dotSmasher.css" type="text/css">
<script src="dotSmasher.js" type="text/javascript"></script>
</head>
<body onLoad="setGameAreaBounds(); startGameTimer()" onResize="setGameAreaBounds()">
<div id="scoreLabel">Score: 0</div>
<div id="pageTitle">DotSmasher</div>
<div id="start">
<button id="startButton" onClick="start()">Start</button>
</div>
<div id="stop">
<button id="stopButton" onClick="pause()">Stop</button>
</div>
<div id="gameArea">
<button id="dot" onClick="detectHit()"></button>
</div>
</body>
</html>
JavaScript Code
Variables count, timer, and difficulty are instantiated at the beginning of the page
var score = 0;
var aWidth;
var aHeight;
var timer;
var count = 30;
var counter = setInterval(startGameTimer, 1000);
var difficulty;
function startGameTimer(){
count -= 1;
if (count <= 0){
clearInterval(counter);
clearTimeout(timer);
alert("Game has ended, Thank you for playing on " + difficulty + "!");
return;
}
}
function setDifficulty(){
var radioButtons = document.getElementsByName("diff");
for (var i = 0; i < radioButtons.length; i++) {
if (radioButtons[i].checked) {
difficulty = radioButtons[i].value;
}
}
}
For some reason i am getting an undefined error and cannot figure out what it could be.
You need to put your script at the top in your page and in head tag, try this:
<script>
function setDifficulty(){
var radioButtons = document.getElementsByName("diff");
for (var i = 0; i < radioButtons.length; i++) {
if (radioButtons[i].checked) {
difficulty = radioButtons[i].value;
alert(difficulty);
}
}
}
</script>
<input type="radio" name="diff" id="easyDiff" value="easy">
<label for="easyDiff">Easy</label>
<input type="radio" name="diff" id="medDiff" value="medium" checked="checked">
<label for="medDiff">Medium</label>
<input type="radio" name="diff" id="hardDiff" value="hard">
<label for="hardDiff">Hard</label>
<input type="submit" value="Start Game!" onclick="setDifficulty();"/>
Here is DEMO