Does anyone know what's wrong with start1()? I know that something is not right but I just can't figure what is it.
I have got this school project where i need to do a quiz and record the time that people need to answer all the questions. I've tried everything i know but nothing works. please help
<body>
<div id="classic">
<input type="button" onclick="start1= setInterval(contador, 1000)" value="yes">
<input type="button" onclick="back1()" value="Menu">
</div>
<div id="quizr" hidden>
<h1> who sings the song </h1>
<div id="P1">
<p>1.'Thinking Out Loud'</p>
A)<input type="radio" name="q1" id="q1r1" > Hozier<br>
B)<input type="radio" name="q1" id="q1r2" > Jason Derulo<br>
C)<input type="radio" name="q1" id="q1r3" > Ed Sheeran<br>
D)<input type="radio" name="q1" id="q1r4" > Mr. Probz<br>
<br>
<input type="button" onclick='go1()' value="next »" >
</div>
<div id="P2" hidden>
<p>2.'GANGNAM STYLE'</p>
A)<input type="radio" name="q15" id="q15r1" > Tori Kelly<br>
B)<input type="radio" name="q15" id="q15r2" > Jessie J<br>
C)<input type="radio" name="q15" id="q15r3" > Beyoncé<br>
D)<input type="radio" name="q15" id="q15r4" > Psy<br>
<br>
<input type="button" onclick='verify1= clearInterval(start1)'value="submit">
</div>
</div>
<div id="result" hidden></div>
function start1()
{
document.getElementById("classic").hidden=true;
document.getElementById("quizr").hidden=false;
}
var t= 0;
function contador()
{
document.getElementById("resultado").innerHTML = ++t;
}
function go1()
{
document.getElementById("P1").hidden= true;
document.getElementById("P2").hidden = false;
}
function verify1()
{
document.getElementById("P2").hidden = true;
document.getElementById("result").hidden = false;
var correctAnswers= 0;
var question1 = document.getElementById("q1r3").checked;
if (question1 === true)
{
correctAnswers = correctAnswers + 1;
}
var question2 = document.getElementById("q2r4").checked;
if (question2 === true)
{
correctAnswers = correctAnswers + 1;
}
document.getElementById("resultado").innerHTML = correctAnswers + "/15" + " " + " correct" + " "+ "answers";
}
This is just a readonly. See the docs:
hidden
Is a Boolean attribute indicates that the element is not yet, or is no longer, relevant. For example, it can be used to hide elements of the page that can't be used until the login process has been completed. The browser won't render such elements. This attribute must not be used to hide content that could legitimately be shown.
What you must really do is:
document.getElementById("classic").style.display = 'none';
document.getElementById("quizr").style.display = 'block';
Related
I am trying to make a small quiz web app using javascript/html. The individual questions on the page are separated by div tags with the same "quiz" class. There are 2 buttons on the page, a previous and a next button. Depending on what the user clicks, the page will display the next quiz on the page by hiding/showing the divs. What I am trying to do is add an input validation to the application. Before the user moves onto the next question I want to make it so that one radio button must be selected, otherwise show an alert box. The radio buttons that belong to the same question all have the same class (i.e. the radio buttons for question 1 all have the same class quiz1). Currently app is able to check which input has been selected (by using if element.checked). Following this logic, I tried using if(!element.checked) create an alert, however the alert box get stuck in a loop. Thus, so far the only other solution I have been able to come up with is to check if at least one radio button within the same class has been selected, which I am unsure how to achieve.
let savedAns = [];
const nextBtn = document.getElementById('next');
const prevBtn = document.getElementById('prev');
const quizes = document.querySelectorAll('.quiz');
const form = document.querySelector('form');
const inputEl = document.querySelectorAll('input');
const total = quizes.length;
//a variable to increment the classes
let ind = 0;
//get all the input elements for each question, assign a class
quizes.forEach(function(element) {
ind++;
let inputs = element.querySelectorAll('input');
inputs.forEach((input) => {
input.classList.add(`quiz${ind}`)
})
})
//keep a track of which question is visible
let count = 0;
//function to hide all the quizes
const hide = function() {
quizes.forEach((element) => {
element.style.display = 'none'
})
}
//show and hide divs when user presses next
nextBtn.addEventListener('click', function() {
if (count < total - 1) {
inputEl.forEach(function(element) {
if (element.checked) {
savedAns[count] = element.value;
console.log(savedAns)
}
})
count++;
} else {
inputEl.forEach(function(element) {
if (element.checked) {
savedAns[count] = element.value;
console.log(savedAns)
}
})
alert('no more questions left')
return
}
hide();
quizes[count].style.display = 'block'
})
prevBtn.addEventListener('click', function() {
if (count > 0) {
count--;
} else {
alert('no more previous questions')
return
}
hide();
quizes[count].style.display = 'block'
})
<div class="content">
<form>
<div class="quiz">
<p>Question 1</p>
<input type="radio" name="answer" value="1">
<input type="radio" name="answer" value="2">
<input type="radio" name="answer" value="3">
</div>
<div class="quiz" style="display: none;">
<p>Question 2</p>
<input type="radio" name="answer" value="1">
<input type="radio" name="answer" value="2">
<input type="radio" name="answer" value="3">
</div>
<div class="quiz" style="display: none;">
<p>Question 3</p>
<input type="radio" name="answer" value="1">
<input type="radio" name="answer" value="2">
<input type="radio" name="answer" value="3">
</div>
<div class="quiz" style="display: none;">
<p>Question 4</p>
<input type="radio" name="answer" value="1">
<input type="radio" name="answer" value="2">
<input type="radio" name="answer" value="3">
</div>
</form>
<button id="prev">Prev</button>
<button id="next">Next</button>
</div>
If there are any other ways to solve the problem, hints towards the right direction is greatly appreciated. I am also writing this application using purely javascript so no jquery please. Thank you.
Since you already know which question is active currently, you can check if any of the input under the active question is checked.
let selectedAnswer = -1;
const activeInputs = quizes[count].querySelectorAll('input');
activeInputs.forEach((input, index) => {
if(input.checked) selectedAnswer = index;
});
if (selectedAnswer === -1) {
alert('Select answer');
return;
}
below is the working code snippet.
let savedAns = [];
const nextBtn = document.getElementById('next');
const prevBtn = document.getElementById('prev');
const quizes = document.querySelectorAll('.quiz');
const form = document.querySelector('form');
const inputEl = document.querySelectorAll('input');
const total = quizes.length;
//a variable to increment the classes
let ind = 0;
//get all the input elements for each question, assign a class
quizes.forEach(function(element) {
ind++;
let inputs = element.querySelectorAll('input');
inputs.forEach((input) => {
input.classList.add(`quiz${ind}`)
})
})
//keep a track of which question is visible
let count = 0;
//function to hide all the quizes
const hide = function() {
quizes.forEach((element) => {
element.style.display = 'none'
})
}
//show and hide divs when user presses next
nextBtn.addEventListener('click', function() {
let selectedAnswer = -1;
const activeInputs = quizes[count].querySelectorAll('input');
activeInputs.forEach((input, index) => {
if(input.checked) selectedAnswer = index;
});
if (selectedAnswer === -1) {
alert('Select answer');
return;
}
if (count < total - 1) {
inputEl.forEach(function(element) {
if (element.checked) {
savedAns[count] = element.value;
console.log(savedAns)
}
})
count++;
} else {
inputEl.forEach(function(element) {
if (element.checked) {
savedAns[count] = element.value;
console.log(savedAns)
}
})
alert('no more questions left')
return
}
hide();
quizes[count].style.display = 'block'
})
prevBtn.addEventListener('click', function() {
if (count > 0) {
count--;
} else {
alert('no more previous questions')
return
}
hide();
quizes[count].style.display = 'block'
})
<div class="content">
<form>
<div class="quiz">
<p>Question 1</p>
<input type="radio" name="answer" value="1">
<input type="radio" name="answer" value="2">
<input type="radio" name="answer" value="3">
</div>
<div class="quiz" style="display: none;">
<p>Question 2</p>
<input type="radio" name="answer" value="1">
<input type="radio" name="answer" value="2">
<input type="radio" name="answer" value="3">
</div>
<div class="quiz" style="display: none;">
<p>Question 3</p>
<input type="radio" name="answer" value="1">
<input type="radio" name="answer" value="2">
<input type="radio" name="answer" value="3">
</div>
<div class="quiz" style="display: none;">
<p>Question 4</p>
<input type="radio" name="answer" value="1">
<input type="radio" name="answer" value="2">
<input type="radio" name="answer" value="3">
</div>
</form>
<button id="prev">Prev</button>
<button id="next">Next</button>
</div>
I am trying to cycle through a list of Div's that have all of my trivia questions inside. I know how to cycle through all of them with an iterator but i just want to know how to grab one Div, run some code, then cycle to the next object in the array after the user has clicked submit, then run the same code etc. I also have each div hidden so they can only see one Div at a time until they are done with the previous question. Very new to Java Script and trying to learn as fast as i can, any tips would greatly be appreciated
<div class="row">
<div class="col-12 questions">
<form name="quiz" onsubmit="return false">
<div class="q1">
<h1>The 'Mountain' is the nickname for which character?</h1>
<input type="radio" name="q" value="wrong" id="q1a">a. Gerold Clegane
<br>
<input type="radio" name="q" value="wrong" id="q1b">b. Sandor clegane
<br>
<input type="radio" name="q" value="wrong" id="q1c">c. Oberyn Martell
<br>
<input type="radio" name="q" value="correct" id="q1d">d. Gregor Clegane
<br>
<button class="submit" type="submit">Submit</button>
</div>
<div class="q2">
<h2>Who is the youngest child of Lord Tywin Lannister?</h2>
<input type="radio" name="q" value="correct" id="q2a">a. Tyrion Lannister
<br>
<input type="radio" name="q" value="wrong" id="q2b">b. Jaime Lannister
<br>
<input type="radio" name="q" value="wrong" id="q2c">c. Cersei Lannister
<br>
<input type="radio" name="q" value="wrong" id="q2d">d. Jon Snow
<br>
<button class="submit" type="submit">Submit</button>
</div>
<div class="q3">
<h3>Who is the King of the North?</h3>
<input type="radio" name="q" value="wrong" id="q3a">a. Bran Stark
<br>
<input type="radio" name="q" value="correct" id="q3b">b. Jon Snow
<br>
<input type="radio" name="q" value="wrong" id="q3c">c. Tommen Baratheon
<br>
<input type="radio" name="q" value="wrong" id="q3d">d. LittleFinger
<br>
<button class="submit" type="submit">Submit</button>
</div>
<div class="q4">
<h4>Who is the head of house Stark?</h4>
<input type="radio" name="q" value="wrong" id="q4a">a. Tyrion Lannister
<br>
<input type="radio" name="q" value="wrong" id="q4b">b. Jon Snow
<br>
<input type="radio" name="q" value="wrong" id="q4c">c. Bran Stark
<br>
<input type="radio" name="q" value="correct" id="q4d">d. Ned Stark
<br>
<button class="submit" type="submit">Submit</button>
</div>
<div class="q5">
<h5>Which persons are the 'Night's Watch' trying to stop by using a giant wall of ice?</h5>
<input type="radio" name="q" value="correct" id="q5a">a. White Walkers
<br>
<input type="radio" name="q" value="wrong" id="q5b">b. Wildings
<br>
<input type="radio" name="q" value="wrong" id="q5c">c. Mother of Dragons
<br>
<input type="radio" name="q" value="wrong" id="q5d">d. Night walkers
<br>
<button class="submit" type="submit">Submit</button>
</div>
</form>
Here is my Javascript
$(document).ready(function () {
console.log("ready!");
var question1 = $('.q1');
var question2 = $('.q2');
var question3 = $('.q3');
var question4 = $('.q4');
var question5 = $('.q5');
var correctAnswers = 0;
var wrongAnswers = 0;
var gameArr = [question1, question2, question3, question4, question5];
function nextGame() {
for (i=0;i<gameArr.length;i++){
//i dont want it to grab every object all at the same time
}
}
nextGame();
console.log(nextGame());
//My startGame button
$('.b1').on("click", function () {
console.log(gameArr[0]);
gameArr[0].show();
});
//Setting up audio for the start screen, make it loop so it never stops running
var audio1 = new Audio("assets/music/startMusic.mp3");
audio1.addEventListener('ended', function () {
this.currentTime = 0;
this.play();
}, false);
audio1.play();
//code to make my quiz responsive
function game() {
var answer = $("input[name='q']:checked").val();
if (answer === "correct") {
alert("Correct!");
correctAnswers = correctAnswers + 1
} else {
wrongAnswers = wrongAnswers + 1
alert("Wrong!");
}
}
//timer
function countdown() {
seconds = 60;
$('#timer').html('<h6>Time Remaining: ' + seconds + '</h6>');
time = setInterval(showCountdown, 1000);
}
function showCountdown() {
seconds--;
$('#timer').html('<h3>Time Remaining: ' + seconds + '</h3>');
if (seconds < 1) {
clearInterval(time);
}
}
//submit your answer
$('.submit').on("click", function () {
//nextGame();
game();
console.log(gameArr);
});
You have to remember the last position.
So you have a variable, call it lastGame or something. This will be a variable at the same level as correctAnswers etc. Start with zero.
Whenever you want to navigate to the next gate, increment this and do a gameArr[lastGame].show();.
Example:
var correctAnswers = 0;
var wrongAnswers = 0;
var gameArr = [question1, question2, question3, question4, question5];
var lastGame = 0;
function nextGame() {
gameArr[lastGame].show();
lastGame++;
}
And on timeout you call nextGame()
make a global iterator increase its value every time the user hits the answer , hide the old div display the new Div
something like this
var question1 = $('.q1');
var question2 = $('.q2');
var question3 = $('.q3');
var question4 = $('.q4');
var question5 = $('.q5');
var correctAnswers = 0;
var wrongAnswers = 0;
var currentIndex = 0;
var gameArr = [question1, question2, question3, question4, question5];
then after the form is submitted
$('.submit').on("click", function () {
//nextGame();
game();
if(currentIndex < (gameArr.length -1 ))
{
// I am using the hide callback which is fired by jQUery after the object is completely hidden
gameArr[currentIndex].hide(function(){
currentIndex++;
gameArr[currentIndex].show();
});
}
});
First off, you should never have more than one button of type submit per form. Move the submit button to just before the form's end tag.
You don't need variables for every question. With your jquery (haven't used jquery in awhile I'm all react now) you should be able to select your questions like this
var questions = $('form div')
Then you will need a current question variable. Maybe have all the divs with a hidden class. When the current question is selected remove that hidden class from the current div.
when the user submits the form you can check if they are at the end of the array of questions if not increment the current question and show the div for the next question. You could hide the previous question or keep it visible (up to you).
Why I'm getting undefined error in Firefox and IE. This code works well in Google Chrome. Here is the full code http://liveweave.com/fUhpiI
this is my html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link href="css/hpstyles.css" rel="stylesheet">
<script src="js/hpjs.js"></script>
</head>
<body>
<form id="hp">
<div>
<h2>1. Which one do you prefer?</h2>
<div>
<input type="radio" name="q1" id="radio1" class="radio" value="9"/>
<label for="radio1">Tea</label>
</div>
<div>
<input type="radio" name="q1" id="radio2" class="radio" value="4"/>
<label for="radio2">Coffee</label>
</div>
<div>
<input type="radio" name="q1" id="radio3" class="radio" value="1"/>
<label for="radio3">Milk</label>
</div>
</div>
<div>
</br>
<div><div>
<button type="button" onclick="hp(this.form)">Check</button>
<input class="reset" type="reset" value="Reset">
</div></div></div>
</form>
<div id="result"></div>
<div id="total"></div>
</body>
</html>
this is javascript
function hp(form)
{
var count1=0, count2=0, count3=0, count4=0, count5=0, count6=0, count7=0, count8=0, count9=0, count10=0,a ;
for(var i=0;i<3;i++){
if (form.q1[i].checked === true)
{
count1++;
}
}
if(count1!==1){
alert("Please Answer 1st Question");
return false;
}
answer1 = (form.q1.value);
a=Math.floor(answer1);
document.getElementById("result").innerHTML= "The selected values are "+"</br>"+answer1;
}
you should declare a answer variable .and you should access "q1" elements by giving index since you have 3 "q1" elements .basically form.q1 is a object NodeList .you can't get value from object NodeList.so actually in your case you should add brake to for loop and find the clicked radio button index .
you should use
answer1 = form.q1[i].value;
instead of
answer1 = form.q1.value;
explain
form.q1 is a object NodeList so
form.q1.value --> undefined since object NodeList/collection has no property "value"
and
form.q1[0] --> HTMLInputElement so
form.q1[0].value --> is not undefined
fixed code .WORKING DEMO http://jsfiddle.net/madhawa11111/3rywkdvf/
function hp(form) {
var i;
var answer;
var count1 = 0,count2 = 0,count3 = 0,count4 = 0,count5 = 0,count6 = 0,count7 = 0,count8 = 0,count9 = 0,count10 = 0, a;
for (i = 0; i < 3; i++) {
if (form.q1[i].checked === true) {
count1++;
break;
}
}
if (count1 !== 1) {
alert("Please Answer 1st Question");
return false;
}
answer1 = form.q1[i].value; //error was here .
a = Math.floor(answer1);
document.getElementById("result").innerHTML = "The selected values are " + "</br>" + answer1;
}
if it worked in google chorm that's because browsers ignore some errors.
I'm creating a mini quiz, if the answer is correct the background will be green, if is wrong will be red
here is the code of HTML
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form class="forma">
<div class="pyetja"><h3>1. The flag if Italy which color has..</h3>
<div class="formafoto"><div class="foto"></div><div class="pergjigjet"><div class="pergjigje">
<div class="pergjigjemajtas">
white and blue
</div>
<div class="pergjigjedjathtas" id="0">
<label><input type="radio" value="1" name="0" unchecked="">right</label>
<label><input type="radio" value="0" name="0" unchecked="">wrong</label>
</div>
</div>
<div class="pergjigje">
<div class="pergjigjemajtas">
white and red
</div>
<div class="pergjigjedjathtas" id="1">
<label><input type="radio" value="1" name="1" unchecked="">right</label>
<label><input type="radio" value="0" name="1" unchecked="">wrong</label>
</div>
</div>
<div class="pergjigjeno">
<div class="pergjigjemajtas">
white red and green
</div>
<div class="pergjigjedjathtas" id="2">
<label><input type="radio" value="1" name="2" unchecked="">right</label>
<label><input type="radio" value="0" name="2" unchecked="">wrong</label>
</div>
</div></div></div></div>
<div class="question">
<input id="buton" type="button" value="Finish!" onClick="getScore(this.form); getResult(this.form);">
<p> <strong class="bgclr">Result = </strong><strong><input class="bgclr1" type="text" size="2" name="percentage" disabled></strong><br><br>
<div id="rezultati"></div>
</div>
</form>
</body>
</html>
and javascript
// Insert number of questions
var numQues = 3;
// Insert number of choices in each question
var numChoi = 2;
// Insert number of questions displayed in answer area
var answers = new Array(2);
// Insert answers to questions
answers[0] = 1;
answers[1] = 1;
answers[2] = 1;
// Do not change anything below here ...
function getScore(form) {
var score = 0;
var currElt;
var currSelection;
for (i=0; i<numQues; i++) {
currElt = i*numChoi;
for (j=0; j<numChoi; j++) {
currSelection = form.elements[currElt + j];
if (currSelection.checked) {
if (currSelection.value == answers[i]) {
score++;
}
}
}
}
var radio1 = document.getElementByName("0").value;
if (answers[0] == radio1) {
document.getElementById("0").style.backgroundColor="#00FF00";
} else {
document.getElementById("0").style.backgroundColor="#e83f3f";
}
if(score > 3) {
document.getElementById("rezultati").innerHTML = "Congratulation!";
} else {
document.getElementById("rezultati").innerHTML = "Try again!";
}
form.percentage.value = score;
form.solutions.value = correctAnswers;
}
// End -->
</script>
I get always red background and if the answer is correct, maybe document.getElementByName("0").value is not getting a number to make true the condition
var radio1 = document.getElementByName("0").value;
if (answers[0] == radio1) {
document.getElementById("0").style.backgroundColor="#00FF00";
} else {
document.getElementById("0").style.backgroundColor="#e83f3f";
}
var radio1 = document.getElementByName("0").value;
if (answers[0] == radio1) {
Probably your error is in this line of code, the id="0" is a div and you are trying to get the value of it, this might result into undefined and the value answer[0] is 1, thus 1 is not equal to radio1, thus it is always getting into the else block.
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/