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

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>

Related

Javascript Local Storage Not Storing Everything

So I want to add local storage to this project but it's only saving the first 2 checkboxes, not all of them. I want to make a habit tracker and you are to check off the days you complete and so when you reload the page, the days you have completed a habit are checked off. so far I only have the basic layout of the page without the actual habit part or the styling. I'm trying to work on the checkbox part first.
Any help will be appreciated. Code is below:
HTML
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
<title>Local Storage Test</title>
</head>
<body>
<!-- <p>Last Saved Item: <span id="saved">_____</span></p>
<input id="username" type="text"></input>
<button onclick="store()">Save</button>
<br><br>
<p id="confirm"></p> -->
<h2 id="Haading">Habbit Tracker</h2><br>
<div class="habbits">
<input type="text" placeholder="Enter A Habbit Here"><button class="add" onclick="add()">Add</button><br><br>
</div>
<div class="days">
<input onclick="save()" type="checkbox" id="Mon">Monday</input>
<br>
<input onclick="save()" type="checkbox" id="Tue">Tuesday</input>
<br>
<input onclick="save()" type="checkbox" id="Thu">Wednesday</input>
<br>
<input onclick="save()" type="checkbox" id="Fri">Thursday</input>
<br>
<input onclick="save()" type="checkbox" id="Sun">Friday</input>
<br>
<input onclick="save()" type="checkbox" id="Sat">Saturday</input>
<br>
<input onclick="save()" type="checkbox" id="Sun">Sunday</input>
</div>
<script src="script.js" charset="utf-8"></script>
</body>
</html>
Javascript
function save(){
var checkbox1 = document.getElementById('Mon');
localStorage.setItem('monday', checkbox1.checked);
var checkbox2 = document.getElementById('Tue');
localStorage.setItem('tuesday', checkbox2.checked);
var checkbox3 = document.getElementById('Wed');
localStorage.setItem('wednesday', checkbox3.checked);
var checkbox4 = document.getElementById('Thu');
localStorage.setItem('thursday', checkbox4.checked);
var checkbox5 = document.getElementById('Fri');
localStorage.setItem('friday', checkbox5.checked);
var checkbox6 = document.getElementById('Sat');
localStorage.setItem('saturday', checkbox6.checked);
var checkbox7 = document.getElementById('Sun');
localStorage.setItem('sunday', checkbox7.checked);
}
function load(){
var checked1 = JSON.parse(localStorage.getItem('monday'));
document.getElementById("Mon").checked = checked1;
var checked2 = JSON.parse(localStorage.getItem('tuesday'));
document.getElementById("Tue").checked = checked2;
var checked3 = JSON.parse(localStorage.getItem('wednesday'));
document.getElementById("Wed").checked = checked3;
var checked4 = JSON.parse(localStorage.getItem('thursday'));
document.getElementById("Thu").checked = checked4;
var checked5 = JSON.parse(localStorage.getItem('friday'));
document.getElementById("Fri").checked = checked5;
var checked6 = JSON.parse(localStorage.getItem('saturday'));
document.getElementById("Sat").checked = checked6;
var checked7 = JSON.parse(localStorage.getItem('sunday'));
document.getElementById("Sun").checked = checked7;
}
load();
This ids for these 3 input fileds are wrong.
<input onclick="save()" type="checkbox" id="Thu">Wednesday</input>
<br>
<input onclick="save()" type="checkbox" id="Fri">Thursday</input>
<br>
<input onclick="save()" type="checkbox" id="Sun">Friday</input>
<br>
So you js code throws an error here:
document.getElementById("Wed").checked = checked3;
Change your html to:
<input onclick="save()" type="checkbox" id="Wed">Wednesday</input>
<br>
<input onclick="save()" type="checkbox" id="Thu">Thursday</input>
<br>
<input onclick="save()" type="checkbox" id="Fri">Friday</input>
<br>
and it will work

HTML/Javascript Radio Button Quiz

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>

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>

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

I am making a questionnaire and am not brilliant with JS. I want to take the results of the radio buttons which have been marked, so either True or False, and then show them on another page. I have the questions in a form.
CODE:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styling/style.css">
<title>1</title>
</head>
<body>
<script>
function sendclick() {
var answers = [document.forms["questionarre"]["clickRule"].value,
document.forms["questionarre"]["404error"].value,
document.forms["questionarre"]["colour"].value,
document.forms["questionarre"]["H2Tag"].value,
document.forms["questionarre"]["SiteMap"].value,
document.forms["questionarre"]["heading"].value,
document.forms["questionarre"]["alttag"].value,
document.forms["questionarre"]["UseAgain"].value];
var count = 0
for (var i = 0; i<answers.length; i++) {
if (answers[i] == "") {
var temp = i+1;
alert("Please complete question "+temp);
break;
}
count++;
}
if (count == answers.length) {
var correct = [document.getElementById("correct1").checked,
document.getElementById("correct2").checked,
document.getElementById("correct3").checked,
document.getElementById("correct4").checked,
document.getElementById("correct5").checked,
document.getElementById("correct6").checked];
//window.open("YourResults.html", "_self")
}
}
/*
for (var i = 0; i<x.length; i++) {
if (x[i] == "") {
var temp = i+1;
// alert("results"+x)//window.open("results"+x);
break;}
}
}function - sendClick end
function opener() {
var text = document.getElementById('correct7').value;
var target = {
non text content : alert("correct")
};
if (text in targetNames) {
window.open(targetNames[text]);
}
}
document.getElementById('name').addEventListener('keyup', opener, false);
*/
</script>
<div id="questionarre_bg">
<form name="questionarre" action="" method="post">
<div id="Question1">
<p class="thicker">How many clicks do developers use to keep the user close to information? </p>
<input type="radio" name="clickRule" value=1>1<br>
<input type="radio" name="clickRule" value=4>4
<input type="radio" name="clickRule" id="correct1" value=3>3<br>
<input type="radio" name="clickRule" value=6>6
</div>
<div id="Question2">
<p class="thicker">How are developers using the 404 Error Page, for keep the users happy?</p>
<input type="radio" name="404error" id="correct2" value="Including links">Including links<br>
<input type="radio" name="404error" value="displaying a video">displaying a video<br>
<input type="radio" name="404error" value="playing music">playing music<br>
</div>
<div id="Question3">
<p class="thicker">Should you rely on colour alone in a website build?</p>
<input type="radio" name="colour" value="Yes">Yes<br>
<input type="radio" name="colour" id="correct3" value="No">No
</div>
<div id="Question4">
<p class="thicker">A H2 Tag is useful for?</p>
<input type="radio" name="H2Tag" id="correct4" value="The disabled autoreaders">The disabled autoreaders<br>
<input type="radio" name="H2Tag" value="Pretty webpages">Pretty webpages<br>
</div>
<div id="Question5">
<p class="thicker" >What is correct name given to page of the websites pages?</p>
<input type="radio" name="SiteMap" value="Tube Map">Tube Map
<input type="radio" name="SiteMap" id="correct5" value="Site Map">Site Map <br>
<input type="radio" name="SiteMap" value="Map">Map
<input type="radio" name="SiteMap" value="Page List">Page List
</div>
<div id="Question6">
<p class="thicker">A webpage heading should do what?</p>
<input type="radio" name="heading" id="correct6" value="Tell the user about the content in a few words">Tell the user about the content in a few words<br>
<input type="radio" name="heading" value="include meaningless text">include meaningless text<br>
<input type="radio" name="heading" value="Be short">Be short<br>
</div>
<div id="Question7">
<p class="thicker">The Alt tag is used for what....</p>
<input type="text" name="alttag" id="correct7" ><br><!--ANSWER__non text content-->
</div>
<div id="Question8">
<p class="thicker">Would you use this website again for information?</p>
<input type="radio" name="UseAgain" value="Yes">Yes<br>
<input type="radio" name="UseAgain" value="No">No<br>
<textarea rows="4" cols="50"></textarea>
</div>
</form>
<button onclick="sendclick()">send</button>
</div>
</div>
</body>
</html>
you could pass the answer through local storage
it would be something like this
//save the info on page 1
//resultArr will be the array holding all the radio results,
//you could get them by jQuery or any other method to you are comfortable with
localStorage.setItem("answers", answers);
// Retrieve the info on page 2
document.getElementById("answer1").innerHTML = localStorage.getItem("answers")[0];
you can read more about it here:
http://www.w3schools.com/html/html5_webstorage.asp

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.

Categories

Resources