HTML/Javascript Radio Button Quiz - javascript

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>

Related

Is there a simpler way to check radio buttons? [duplicate]

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>

Why do I get Uncaught TypeError while I've defined it?

I'm trying to make a quiz, here is the html :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>English Test</title>
<link rel="stylesheet" href="testCss.css">
</head>
<body>
<br>
<div style="font-size:20px">
<p>Please choose the correct answer and at the end tap the score button. </p>
<br>
<div>
2. I
<select id="question2">
<option value="_">_</option>
<option value="Am">am</option>
<option value="Is">is</option>
<option value="Are">are</option>
</select>
22 years old.
<span id="question2_answer"></span>
</div>
<br>
<br>
<div>
101. When can we meet again?
<span id="question101_answer"></span>
<div>
<input type="radio" name="question101" > When are you free?<br>
<input type="radio" name="question101" > It was two days ago. <br>
<input type="radio" name="question101" > Can you help me?
</div>
</div>
<br>
<br>
<div>
8. What is your father like?
<span id="question8_answer"></span>
<div>
<input type="radio" name="question8" > He likes listenning to music.<br>
<input type="radio" name="question8" > He likes to play football. <br>
<input type="radio" name="question8" > He is friendly.<br>
<input type="radio" name="question8" > He has a car.
</div>
</div>
<br>
<br>
<button id="button1" class="button" onclick="viewScore()">Score Result</button>
<br>
<input type="text" id="grade1" value="" readonly>
<br>
<script src="testJs.js"></script>
and here is the testJs.js that i used:
var score = 0;
function viewScore() {
var answer2 = document.getElementById("question2").value;
var answer8 = document.getElementsByName("question8");
var answer101 = document.getElementsByName("question101").value;
if (answer2 == "Am") {
document.getElementById("question2_answer").style.color = "green";
document.getElementById("question2_answer").innerHTML = "&#10004";
score += 1;
} else {
document.getElementById("question2_answer").style.color = "red";
document.getElementById("question2_answer").innerHTML = "&#10006 Wrong!";
}
if (answer8[2].checked) {
document.getElementById("question8_answer").style.color = "green";
document.getElementById("question8_answer").innerHTML = "&#10004";
score += 1;
} else {
document.getElementById("question8_answer").style.color = "red";
document.getElementById("question8_answer").innerHTML = "&#10006 Wrong!";
}
if (answer101[0].checked) {
document.
getElementsById("question101_answer").style.color = "green";
document.getElementsById("question101_answer").innerHTML = "&#10004";
score += 1;
} else {
document.getElementsByID("question101_answer").style.color = "red";
document.getElementsByID("question101_answer").innerHTML = "&#10006 Wrong!";
}
if (score<=5) {
document.getElementById("grade1").value = " Your total score is: "+ score+" Your level is: "+"Elementary.";
} else if(score<=8){
document.getElementById("grade1").value = " Your total score is: "+ score+" Your level is: "+"Pre Intermediate.";
}else if(score<=15){
document.getElementById("grade1").value = " Your total score is: "+ score+" Your level is: "+"Intermediate.";
}else{
document.getElementById("grade1").value = " Your total score is: "+ score+" Your level is: "+"Upper Intermediate.";
}
console.log(score);
score = 0;
}
However, I'm getting following error on question 101. I check it several times and I have no idea where does this error coming from ! It refers to question 101 and mentions cannot read property '0' of undefined.
Thanks for any help in advance.
testJs.js:26 Uncaught TypeError: Cannot read property '0' of undefined
at viewScore (testJs.js:26)
at HTMLButtonElement.onclick (testHTML.html:57)
This is happening because in this line:
var answer101 = document.getElementsByName("question101").value;
you are putting the value of the input (which is NULL or UNDEFINED because the HTMLCollection returned by getElementsByName (note the plural) doesn't have a value property) into the var answer101 and NOT the input itself.
To fix this, change the above line to:
var answer101 = document.getElementsByName("question101");
You have to select array (not value) for var answer101
var answer101 = document.getElementsByName("question101");
And correct if content for answer101
if (answer101[0].checked) {
document.getElementById("question101_answer").style.color = "green";
document.getElementById("question101_answer").innerHTML = "&#10004";
score += 1;
} else {
document.getElementById("question101_answer").style.color = "red";
document.getElementById("question101_answer").innerHTML = "&#10006 Wrong!";
}

HTML based troubleshooting decision tree

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>

Undefined error in Mozilla Firefox

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.

Calling string from one function into another doesent seem to work., why?

So I have this code and it does not seem to work. The thing I want it to do is to call the "together" from the function "go" in the function "second". What am i doing wrong?
The program was initially supposed to take what is in the input-text and add it with the ".com" or the ".no"(depending on what u checked) and redirect to that page. But I only want to call the "together" in the "second" function. Is there any better way to do it?
<!doctype html>
<html>
<head>
<title>A Basic Form</title>
<link rel="stylesheet" type="text/css">
<style type="text/css">
</style>
</head>
<body>
<fieldset>
<legend>Redirection: </legend>
<div>
<label>Where do you want to go?</label>
<input type="text" id="input" name="input" size="7">
<input type="button" id="submit" name="submit" value="Submit" onclick="go()">
</div>
<div>
<input type="radio" id="no" name="end" value=".no">
<label for="no">.no</label><br />
<input type="radio" id="com" name="end" value=".com">
<label for="com">.com</label>
</div>
</fieldset>
<script type="text/javascript">
var end = "";
var input = document.getElementById("input").value;
function go(end, input){
if (document.getElementById("no").checked){
end = document.getElementById("no").value;
}else if (document.getElementById("com").checked){
end = document.getElementById("com").value;
}else{
alert("Please Choose a category!");
}
var together = input + end;
// window.location.replace("http://www." + together);
}
second(together);
function second(together){
alert(together);
}
</script>
</body>
</html>
function go(end, input){
if (document.getElementById("no").checked){
end = document.getElementById("no").value;
}else if (document.getElementById("com").checked){
end = document.getElementById("com").value;
}else{
alert("Please Choose a category!");
}
var together = input + end;
// window.location.replace("http://www." + together);
} // remove this
second(together);
} // add this

Categories

Resources