Issue with JavaScript quiz if radi is checked - javascript

Below it's my code that I made and I do not want to skip the question without checking any option from the question when I press button Next and I tried by using: checked as the code below shows, but it does not work.
And also it does not show quiz results when I finish the quiz and click the Submit button, it does not show results how many questions I got correct like the JS code is?
<div id = "results">
<form id="quiz-form">
<div class="quiz">
<div id="pytja1" class="questions1">
<span class="quest1">I am a ?</span><br/>
<input type="radio" name="q1" value="male" id="correct"> Male<br/>
<input type="radio" name="q1" value="female" id="correct2"> Female<br/>
<input type="radio" name="q1" value="other"> Other<br/>
<input class="bot" type="button" value="Next" />
</div>
<div id="pytja2" class="questions2">
<span class="quest2">Football has letters ?</span><br/>
<input type="radio" name="q2" value="8" class="correct"> 8<br/>
<input type="radio" name="q2" value="5"> 5<br/>
<input type="radio" name="q2" value="6"> 6<br/>
<input class="bot" type="button" value="Next" />
</div>
<div id="pytja3" class="questions3">
<span class="quest3">VW stands for ?</span><br/>
<input type="radio" name="q3" value="BMW" /> BMW <br/>
<input type="radio" name="q3" value="Volkswagen" class="correct" /> Volkswagen<br/>
<input type="radio" name="q3" value="Audi" /> Audi<br/>
<input class="bot" type="button" value="Next" />
</div>
<div id="pytja4" class="questions4">
<span class="quest4">What year it is ?</span><br/>
<input type="radio" name="q4" value="2017" /> 2017<br/>
<input type="radio" name="q4" value="2015" /> 2015<br/>
<input type="radio" name="q4" value="2019" class="correct" /> 2019<br/>
<input id="bot-submit" type="submit" value="Submit" />
</div>
</div>
</form>
</div>
form {
width: 100%;
position: relative;
float: left;
padding-top: 50px;
}
.quiz {
margin: 0px auto;
width: 250px;
height: 100px;
position: absolute;
top: 460px;
left: 42%;
}
.quest1,
.quest2,
.quest3,
.quest4 {
background-color: cadetblue;
font-size: 22px;
}
.questions1 {
margin-left: 28px;
background-color: cyan;
width: 220px;
padding: 10px;
font-size: 20px;
}
.questions2 {
background-color: red;
}
.questions3 {
background-color: greenyellow;
}
.questions4 {
background-color: olivedrab;
}
.bot {
margin-top: 10px;
}
#pytja2,
#pytja3,
#pytja4 {
margin-left: 28px;
display: none;
width: 220px;
padding: 10px;
font-size: 20px;
}
let question1 = document.getElementById('pytja1');
let question2 = document.getElementById('pytja2');
let question3 = document.getElementById('pytja3');
let question4 = document.getElementById('pytja4');
let result = document.getElementById('bot-submit');
let nextButtons = document.querySelectorAll('.bot');
for (let i = 0; i < nextButtons.length; i++) {
let nextQuestion = nextButtons[i];
nextQuestion.onclick = function() {
switchToNextQuestion(this);
};
}
function switchToNextQuestion(nextQuestion) {
let parentId = nextQuestion.parentNode.id;
if (parentId === 'pytja1') {
question1.style.display = 'none';
question2.style.display = 'block';
} else if (parentId === 'pytja2') {
question2.style.display = 'none';
question3.style.display = 'block';
} else if (parentId === 'pytja3') {
question3.style.display = 'none';
question4.style.display = 'block';
}
}
function radioChecked(form) {
let checked = form.querySelector("input[type=radio]:checked");
let value;
if (!checked) {
alert("You need to select one option");
return;
} else {
value = checked.value;
}
results.push(value);
}
let questions = [
{
prompt: "I am a ?\n(a) Male\n\ (b) Female\n(c) Others",
answer: "a"
},
{
prompt: "Football has letters ?\n(a) 8\n\ (b) 5\n(c) 6",
answer: "a"
},
{
prompt: "VW stands for ?\n(a) BMW \n\ (b) Volkswagen\n(c) Audi",
answer: "b"
},
{
prompt: "What year it is ?\n(a) 2017 \n\ (b) 2015\n(c) 2019",
answer: "c"
}
];
let score = 0;
for(let i = 0; i < questions.length; i++){
let response = window.prompt(questions[i].prompt);
if(response == questions[i].answer){
score++;
alert("Correct!");
} else {
alert("WRONG!");
}
}
alert("you got " + score + "/" + questions.length);
document.getElementById("bot-submit").addEventListener("click",
function(e){
e.preventDefault();
})

Check if this is what you want. You have a lots of unnecessary code but i'm not getting into that now. You just needed the questions array for the window prompt to work.
let question1 = document.getElementById('pytja1');
let question2 = document.getElementById('pytja2');
let question3 = document.getElementById('pytja3');
let question4 = document.getElementById('pytja4');
let result = document.getElementById('bot-submit');
let nextButtons = document.querySelectorAll('.bot');
let currentQues;
for (let i = 0; i < nextButtons.length; i++) {
let nextQuestion = nextButtons[i];
nextQuestion.onclick = function() {
switchToNextQuestion(this);
};
}
function switchToNextQuestion(nextQuestion) {
let parentId = nextQuestion.parentNode.id;
if (parentId === 'pytja1') {
question1.style.display = 'none';
question2.style.display = 'block';
} else if (parentId === 'pytja2') {
question2.style.display = 'none';
question3.style.display = 'block';
} else if (parentId === 'pytja3') {
question3.style.display = 'none';
question4.style.display = 'block';
}
}
function radioChecked(form) {
let checked = form.querySelector("input[type=radio]:checked");
let value;
if (!checked) {
alert("You need to select one option");
return;
} else {
value = checked.value;
}
results.push(value);
}
let questions = [
{
prompt: "I am a ?\n(a) Male\n\ (b) Female\n(c) Others",
answer: "a"
},
{
prompt: "Football has letters ?\n(a) 8\n\ (b) 5\n(c) 6",
answer: "a"
},
{
prompt: "VW stands for ?\n(a) BMW \n\ (b) Volkswagen\n(c) Audi",
answer: "b"
},
{
prompt: "What year it is ?\n(a) 2017 \n\ (b) 2015\n(c) 2019",
answer: "c"
}
];
let score = 0;
for(let i = 0; i < questions.length; i++){
let response = window.prompt(questions[i].prompt);
console.log(response);
if(response == questions[i].answer){
score++;
alert("Correct!");
}
else if(response !== questions[i].answer && response !== 'a' && response !== 'b' && response !== 'c'){
alert("You need to select one option");
i--;
}
else {
alert("WRONG!");
}
}
alert("you got " + score + "/" + questions.length);
document.getElementById("bot-submit").addEventListener("click",
function(e){
e.preventDefault();
})
form {
width: 100%;
position: relative;
float: left;
padding-top: 50px;
}
.quiz {
margin: 0px auto;
width: 250px;
height: 100px;
position: absolute;
top: 460px;
left: 42%;
}
.quest1,
.quest2,
.quest3,
.quest4 {
background-color: cadetblue;
font-size: 22px;
}
.questions1 {
margin-left: 28px;
background-color: cyan;
width: 220px;
padding: 10px;
font-size: 20px;
}
.questions2 {
background-color: red;
}
.questions3 {
background-color: greenyellow;
}
.questions4 {
background-color: olivedrab;
}
.bot {
margin-top: 10px;
}
#pytja2,
#pytja3,
#pytja4 {
margin-left: 28px;
display: none;
width: 220px;
padding: 10px;
font-size: 20px;
}
<div id = "results">
<form id="quiz-form">
<div class="quiz">
<div id="pytja1" class="questions1">
<span class="quest1">I am a ?</span><br/>
<input type="radio" name="q1" value="male" id="correct"> Male<br/>
<input type="radio" name="q1" value="female" id="correct2"> Female<br/>
<input type="radio" name="q1" value="other"> Other<br/>
<input class="bot" type="button" value="Next" />
</div>
<div id="pytja2" class="questions2">
<span class="quest2">Football has letters ?</span><br/>
<input type="radio" name="q2" value="8" class="correct"> 8<br/>
<input type="radio" name="q2" value="5"> 5<br/>
<input type="radio" name="q2" value="6"> 6<br/>
<input class="bot" type="button" value="Next" />
</div>
<div id="pytja3" class="questions3">
<span class="quest3">VW stands for ?</span><br/>
<input type="radio" name="q3" value="BMW" /> BMW <br/>
<input type="radio" name="q3" value="Volkswagen" class="correct" /> Volkswagen<br/>
<input type="radio" name="q3" value="Audi" /> Audi<br/>
<input class="bot" type="button" value="Next" />
</div>
<div id="pytja4" class="questions4">
<span class="quest4">What year it is ?</span><br/>
<input type="radio" name="q4" value="2017" /> 2017<br/>
<input type="radio" name="q4" value="2015" /> 2015<br/>
<input type="radio" name="q4" value="2019" class="correct" /> 2019<br/>
<input id="bot-submit" type="submit" value="Submit" />
</div>
</div>
</form>
</div>

Related

html5 validation on checkboxes

HTML5 form validation will not cover the situation where, starting from a group of checkboxes, at least one of them is checked. If a checkbox has the required attribute it must be checked, this is what I can get at most.
So I built a workaround that works fine (code in the snippet). The issue is that this works for one group of checkboxes. But I want my code to be valid even if I add more chackboxes groups. I need a suggestion on how to make it valid for multiple groups.
Any idea?
function bindItemsInput() {
var inputs = document.querySelectorAll('[name="option[]"]')
var radioForCheckboxes = document.getElementById('radio-for-checkboxes')
function checkCheckboxes () {
var isAtLeastOneServiceSelected = false;
for(var i = inputs.length-1; i >= 0; --i) {
if (inputs[i].checked) isAtLeastOneCheckboxSelected = true;
}
radioForCheckboxes.checked = isAtLeastOneCheckboxSelected
}
for(var i = inputs.length-1; i >= 0; --i) {
inputs[i].addEventListener('change', checkCheckboxes)
}
}
bindItemsInput() // call in window onload
.checkboxs-wrapper {
position: relative;
}
.checkboxs-wrapper input[name="radio-for-required-checkboxes"] {
position: absolute;
margin: 0;
top: 0;
left: 0;
width: 100%;
height: 100%;
-webkit-appearance: none;
pointer-events: none;
border: none;
background: none;
}
<form>
<div class="checkboxs-wrapper">
<input id="radio-for-checkboxes" type="radio" name="radio-for-required-checkboxes" required/>
<input type="checkbox" name="option[]" value="option1"/>
<input type="checkbox" name="option[]" value="option2"/>
<input type="checkbox" name="option[]" value="option3"/>
</div>
<input type="submit" value="submit"/>
</form>
A second snippet with the relevant HTML (not working, goal of the question is to fix this). It will have now the same ID for the radio button: that is invalid and is the reason of the question:
function bindItemsInput() {
var inputs = document.querySelectorAll('[name="option[]"]')
var radioForCheckboxes = document.getElementById('radio-for-checkboxes')
function checkCheckboxes () {
var isAtLeastOneServiceSelected = false;
for(var i = inputs.length-1; i >= 0; --i) {
if (inputs[i].checked) isAtLeastOneCheckboxSelected = true;
}
radioForCheckboxes.checked = isAtLeastOneCheckboxSelected
}
for(var i = inputs.length-1; i >= 0; --i) {
inputs[i].addEventListener('change', checkCheckboxes)
}
}
bindItemsInput() // call in window onload
.checkboxs-wrapper {
position: relative;
}
.checkboxs-wrapper input[name="radio-for-required-checkboxes"] {
position: absolute;
margin: 0;
top: 0;
left: 0;
width: 100%;
height: 100%;
-webkit-appearance: none;
pointer-events: none;
border: none;
background: none;
}
<form>
<div class="checkboxs-wrapper">
<input id="radio-for-checkboxes" type="radio" name="radio-for-required-checkboxes" required/>
<input type="checkbox" name="option[]" value="option1"/>
<input type="checkbox" name="option[]" value="option2"/>
<input type="checkbox" name="option[]" value="option3"/>
</div>
<div class="checkboxs-wrapper">
<input id="radio-for-checkboxes" type="radio" name="radio-for-required-checkboxes" required/>
<input type="checkbox" name="products[]" value="option1"/>
<input type="checkbox" name="products[]" value="option2"/>
<input type="checkbox" name="products[]" value="option3"/>
</div>
<input type="submit" value="submit"/>
</form>
The form will be valid if at least on products[] checkbox and one option[] checkbox is checked. So I need the javascript to run indipendently for option[] and for products[]. If I have selected one item in groups[] but none in products[] then only products will be surrounded by the box and marked for completition
So this what I imagine you are looking for:
const myForm = document.forms['my-form']
myForm.addEventListener('change', bindItemsInput) // global change event listener
function bindItemsInput(e) //
{
if (!e.target.matches('div.checkboxs-wrapper input[type=checkbox]')) return
// to reject unconcerned checkbox
let groupDiv = e.target.closest('div.checkboxs-wrapper')
, radioGroup = groupDiv.querySelector('input[type=radio]')
, checkGroup = groupDiv.querySelectorAll('input[type=checkbox]')
;
radioGroup.checked = [...checkGroup].reduce((flag,chkBx)=>flag || chkBx.checked, false)
}
// ------ verification part-------------------
myForm.onsubmit=e=> // to verify
{
e.preventDefault() // disable submit for testing
console.clear()
// chexboxes checked values:
let options = [...myForm['option[]'] ].reduce((r,s)=>{ if (s.checked) r.push(s.value);return r},[])
, products = [...myForm['product[]'] ].reduce((r,s)=>{ if (s.checked) r.push(s.value);return r},[])
console.log('options = ', JSON.stringify( options ))
console.log('products = ', JSON.stringify( products ))
myForm.reset() // clear anything for new testing
console.log(' form reseted')
}
<form name="my-form">
<div class="checkboxs-wrapper">
<input type="radio" name="rGroup_1" required >
<input type="checkbox" name="option[]" value="option1">
<input type="checkbox" name="option[]" value="option2">
<input type="checkbox" name="option[]" value="option3">
</div>
<div class="checkboxs-wrapper">
<input type="radio" name="rGroup_2" required>
<input type="checkbox" name="product[]" value="product1">
<input type="checkbox" name="product[]" value="product2">
<input type="checkbox" name="product[]" value="product3">
</div>
<button type="submit">submit</button>
</form>
if i understant. so you have to give another id and another name of course, try this:
function bindItemsInput() {
var inputs = $("input[type=checkbox]");
var radios = $("input[type=radio]");
function checkCheckboxes () {
var isAtLeastOneServiceSelected = false;
for(var i = inputs.length-1; i >= 0; --i) {
if (inputs[i].checked) isAtLeastOneCheckboxSelected = true;
}
radios.each( function(){
$(this).checked = $(this).siblings($("input[type=checkbox]:checked")).length > 0;
});
}
for(var i = inputs.length-1; i >= 0; --i) {
inputs[i].addEventListener('change', checkCheckboxes)
}
}
Using jQuery this can be done with a lot less code.
$(document).ready(function() {
var checkCheckboxesInSameGroup = function() {
var inputs = $(this).children("input[name='option[]']");
var radio = $(this).children("input[name^='radio-for-group']")[0];
radio.checked = inputs.is(":checked");
};
$(".checkboxs-wrapper").on('change', checkCheckboxesInSameGroup);
});
.checkboxs-wrapper {
position: relative;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="checkboxs-wrapper">
<input type="radio" name="radio-for-group1" required/>
<input type="checkbox" name="option[]" value="option1"/>
<input type="checkbox" name="option[]" value="option2"/>
<input type="checkbox" name="option[]" value="option3"/>
</div>
<div class="checkboxs-wrapper">
<input type="radio" name="radio-for-group2" required/>
<input type="checkbox" name="option[]" value="option1"/>
<input type="checkbox" name="option[]" value="option2"/>
<input type="checkbox" name="option[]" value="option3"/>
</div>
</form>

How to fix: adlistener for radio button for if else calculation

I'm trying to create a BMR calculation embedded in my site. I have it working except for the gender portion (if male vs female, different calculations)
I understand that I need an adlistener but doesn't seem to be working. I think I am not referencing it properly.
Here's my code:
var theForm = document.forms["RMRform"];
var bmr;
function RMRcalc() {
var weight = document.getElementById("weight").value;
var height = document.getElementById("height").value;
var age = document.getElementById("age").value;
var gender = document.getElementById("gender").value;
var rad = document.myForm.myRadios;
var prev = null;
for (var i = 0; i < rad.length; i++) {
rad[i].addEventListener('change', function() {
(prev) ? console.log(prev.value): null;
if (this !== prev) {
prev = this;
}
console.log(this.value)
});
}
var activitylevel = new Array();
activitylevel["sedentary"] = 1.2;
activitylevel["low"] = 1.3;
activitylevel["moderate"] = 1.5;
activitylevel["high"] = 1.7;
function getActivityLevel() {
var activityLevelamount = 0;
var theForm = document.forms["RMRform"];
var selectedActivity = theForm.elements["activity"];
activityLevelamount = activitylevel[selectedActivity.value];
return activityLevelamount;
}
if (i = this) {
bmr = ((10 * weight) + (6.25 * height) - (5 * age) - 161) * getActivityLevel();
} else {
bmr = ((10 * weight) + (6.25 * height) - (5 * age) + 5) * getActivityLevel();
}
}
document.getElementsByTagName("button")[0].addEventListener("click", function() {
RMRcalc();
document.getElementById('results').innerHTML = bmr;
})
body {
font: 15px gothic, sans-serif;
letter-spacing: 1px;
}
input {
width: 100%;
}
input[type=number] {
border: none;
border-bottom: 1px solid grey;
}
button[type=button] {
background-color: #ddcecb;
border: none;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
color: #95483e;
padding: 16px 32px;
text-decoration: none;
letter-spacing: 1px;
margin: 4px 2px;
}
input[type=text]:focus {
border: 1px solid #555;
}
.form-inline label {
margin: 5px 10px 5px 0;
}
#media (max-width: 800px) {
.form-inline input {
margin: 10px 0;
}
.form-inline {
flex-direction: column;
align-items: stretch;
}
<form action="" id="RMRform">
<label for='gender' class="inlinelabel">
Female </label>
<input type="radio" id="gender" name="gender" value="fem" checked onclick="RMRcalc()" /><br>
<label for='gender' class="inlinelabel">
Male </label>
<input type="radio" id="gender" name='gender' value="masc" onclick="RMRcalc()" /> <br> Weight (kg):<br>
<input type="number" id="weight"><br><br> Height (cm):<br>
<input type="number" id="height"><br><br> Age (years):<br>
<input type="number" id="age"><br><br> Activity Level:
<select id="activity" name="activity">
<option value="sedentary">sedentary (1-2x/week)</option>
<option value="low">low (2-3x/week)</option>
<option value="moderate">moderate (3-4x/week)</option>
<option value="high">high (5x/week)</option>
</select>
</form> <br>
<button type="button" onclick="">
calculate</button>
<p>Your Daily Estimated Requirements</p>
<div id="results"></div>
With this, there's just no calculation showing.
Thanks in advance!
A closing } is missing for the #media query.
There shouldn't be a variable declaration in your if condition: if (var i=this). Remove the var.
Both of your radio input have the same id="gender". Id's should be unique. Consider using a class instead. This will cause problems when you later use the gender variable for your if male vs female calculations because of this selector:
var gender = document.getElementById("gender").value;
For rad to be defined in your loop...
var rad = document.myForm.myRadios;
...you'll need to change myRadios to gender, because that's the name of your radio inputs. You'll also need to give your form the name myForm.
<form action="" id="RMRform" name="myForm">
Perhaps you're looking for something in this region...
function calc () {
const gender = document.querySelector('input[name="gender"]:checked').value,
weight = document.getElementById('weight').value,
height = document.getElementById('height').value,
age = document.getElementById('age').value,
activity = document.getElementById('activity').value;
// calculate base metric value
let metricBase = ((10 * weight) + (6.25 * height) - (5 * age));
// calculate per gender
metricBase = (gender === 'fem') ? metricBase - 161 : metricBase + 5;
// calculate with inline activity values
const bmr = Math.round( metricBase * parseFloat(activity) );
// format caloric intake output
document.getElementById('results').innerHTML = `${bmr.toLocaleString()} calories/day`;
}
// prevents form change listener until after first calculation
let firstCalc = true;
document.getElementById('calc').addEventListener('click', () => {
if (firstCalc) document.querySelector('form').onchange = calc;
firstCalc = false;
calc();
}, false);
body {
}
body, input {
font-family: Arial,"Helvetica Neue",Helvetica,sans-serif;
font-size: 14px;
letter-spacing: 1px;
}
input[type="radio"] {
display: inline-block;
width: 1rem;
}
input[type="number"] {
border: none;
border-bottom: 1px solid #ccc;
}
.group {
padding: .5rem 0;
}
<form>
<div class="group">
<label class="radio">
<input type="radio" name="gender" value="fem" checked />
Female
</label>
<label class="radio">
<input type="radio" name='gender' value="masc" />
Male
</label>
</div>
<div class="group">
<label for="weight">Weight (kg):</label>
<input type="number" id="weight" value="79" />
</div>
<div class="group">
<label for="weight">Height (cm):</label>
<input type="number" id="height" value="172" />
</div>
<div class="group">
<label for="weight">Age (years):</label>
<input type="number" id="age" value="22" />
</div>
<div class="group">
<label for="activity">Activity Level:</label>
<select id="activity">
<option value="1.2" selected>Sedentary (1-2x/week)</option>
<option value="1.3">Low (2-3x/week)</option>
<option value="1.5">Moderate (3-4x/week)</option>
<option value="1.7">High (5x/week)</option>
</select>
</div>
<button type="button" id="calc">Calculate</button>
</form>
<p id="results"></p>
Here is what i see (i am quite new to JS so i may not see everything) :
There is no opening head tag (not sure if that's a problem).
The gender radio buttons both have the same id. IDs should be unique. And because of this my guess is that this code should only give you the value for fem no ?:
html:
<input type="radio" id="gender" name="gender" value="fem" checked
onclick="RMRcalc()" />
<input type="radio" id="gender" name='gender' value="masc"
onclick="RMRcalc()" />
js:
var gender = document.getElementById("gender").value;
In your for-loops i would use let instead of var, otherwise you might get in trouble someday. Checkout this post.
for (let i = 0; i < rad.length; i++) {
rad[i].addEventListener('change', function () {
I didn't understand this in your function RMRcalc : if (var i = this)

Using arrays to produce an output from a form. How do i change the order of this output?

The code below produces an output of
Apple,Orange
Sliced,Diced
Option1 Option2 Option3 Option4 ,Option1 Option2 Option3 Option4
I would like the output to be
Apple
Sliced
Option1 Option2 Option3 Option4
Orange
Diced
Option1 Option2 Option3 Option4
addOptions() creates the arrays from a form and showOptions() replaces elements with the array.
What needs to be changed in order to achieve this type of output? Please see this snippet
var fruit
var prep
var saladsArr = [];
var salad = {
"theFruit": []
, "thePrep": []
, "theOpt": []
};
function clickFruit() {
fruit = document.getElementById('theTable').theFruitRad.value;
console.log(fruit);
}
function clickPrep() {
prep = document.getElementById('theTable').thePrepRad.value;
console.log(prep);
}
// Create Arrays
function addOrder() {
addOptions(document.getElementById('theTable'));
}
function addOptions(frm) {
var buffTop = "";
for (var i in frm.theFruitRad) {
if (frm.theFruitRad[i].checked) salad.theFruit.push(frm.theFruitRad[i].value);
}
for (var i in frm.thePrepRad) {
if (frm.thePrepRad[i].checked) salad.thePrep.push(frm.thePrepRad[i].value);
}
for (var i in frm.chkbox) {
if (frm.chkbox[i].checked) {
buffTop += frm.chkbox[i].value + " "
}
}
salad.theOpt.push(buffTop);
console.log(saladsArr.length);
saladsArr.push(salad);
resetForms();
}
function showOptions(frm) {
for (var i = 0; i < saladsArr.length; i++) {
var salad = saladsArr[i];
var html_salad = "<div class='resFruit" + [i] + "'>" + salad.theFruit + "</div>";
html_salad += "<div class='resPrep" + [i] + "'>" + salad.thePrep + "</div>";
html_salad += "<div class='resOpt" + [i] + "'>" + salad.theOpt + "</div><br>";
}
document.getElementById('finResults').innerHTML = html_salad;
}
function test() {
console.log(salad);
console.log(salad.theFruit);
console.log(salad.thePrep);
console.log(salad.theOpt);
}
function resetForms() {
document.getElementById("theTable").reset();
}
div{
background:white;
}
.resFruit {
height: auto;
background: yellow;
color: black;
width: auto;
}
.resPrep {
height: auto;
background: green;
color: black;
width: auto;
}
.resOpt {
height: auto;
background: orange;
color: black;
width: auto;
}
table {
color: white;
}
#left {
background: red;
width: 50%;
height: 100%;
float: left;
color: white;
}
#right {
background: blue;
width: 50%;
height: 100%;
float: left;
color: white;
}
#inputButton {
vertical-align: bottom;
}
<html>
<head>
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel=stylesheet type="text/css" href="temp.css" />
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="temp1.js"></script>
</head>
<body bgcolor="#FFFFFF" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
<div id="left">
<form id="theTable"> <b><u>Fruit</u></b>
<br>
<label class="rad">
<input required required type="radio" name="theFruit" id="theFruitRad" onclick="clickFruit()" value="Apple" /><i></i> Apple</label>
<br>
<label class="rad">
<input required type="radio" name="theFruit" id="theFruitRad" onclick="clickFruit()" value="Orange" /> <i></i> Orange</label>
<br>
<label class="rad">
<input required type="radio" name="theFruit" id="theFruitRad" onclick="clickFruit()" value="Banana" /> <i></i> Banana</label>
<br>
<label class="rad">
<input required type="radio" name="theFruit" id="theFruitRad" onclick="clickFruit()" value="Pear" /> <i></i> Pear</label>
<br> <b><u><br>Prep</u></b>
<br>
<label class="rad">
<input type="radio" name="prep" id="thePrepRad" onclick="clickPrep()" value="Sliced" /> <i></i> Sliced</label>
<br>
<label class="rad">
<input type="radio" name="prep" id="thePrepRad" onclick="clickPrep()" value="Diced" /> <i></i> Diced</label>
<br>
<label class="rad">
<input type="radio" name="prep" id="thePrepRad" onclick="clickPrep()" value="Peeled" /> <i></i> Peeled</label>
<br>
<label class="rad">
<input type="radio" name="prep" id="thePrepRad" onclick="clickPrep()" value="Whole" /> <i></i> Whole</label>
<br> <b><u>Options</u></b><br>
<label class="ckb">
<input type="checkbox" name="chkbox1" id="chkbox" value="Option1" /> <i></i> Option1</label>
<br>
<label class="ckb">
<input type="checkbox" name="chkbox1" id="chkbox" value="Option2" /> <i></i> Option2</label>
<br>
<label class="ckb">
<input type="checkbox" name="chkbox1" id="chkbox" value="Option3" /> <i></i> Option3</label>
<Br>
<label class="ckb">
<input type="checkbox" name="chkbox1" id="chkbox" value="Option4" /> <i></i> Option4</label>
</Br>
</form>
</div>
<div id="right">
<div id="finResults"></div>
<center>
<input id="inputButton" type="button" value="Add" onClick="addOrder()" />
<input id="inputButton" type="button" value="test" onClick="test()" />
<input id="inputButton" type="button" value="Show Results" onClick="showOptions(document.getElementById('theTable'))" /> </center>
</div>
</body>
</html>
In order to get the desired output, you just need to add a for loop to your test function as follows:
function test() {
console.log(salad);
for(var i = 0; i < salad.theFruit.length; i++) {
console.log(salad.theFruit[i] || '');
console.log(salad.thePrep[i] || '');
console.log(salad.theOpt[i] || '');
console.log('');
}
}
Hope that's what you want.
When you print an array, it prints all the elements at once, separated by a comma. That was the case in your code which printed all the fruits at once, followed by preps and opts.
Adding a loop, we print the element at a particular index from all the 3 arrays at once. Thus, the element in the fruits array at the first position is printed, followed by the first element in the preps array, and the opts array. Then the elements at second position from all the 3 arrays and so on.

Another Order form with radio buttons, but need no taxes, subtotals or quantities,

Still weeks into Javascript class it was a short fast pace class and I have this final project that has three class of orders with 3 options to chose from. All are radio type with amounts. There is no quantities listed nor is there tax or subtotal. The Total box should have a running balance and will clear when the Clear button is clicked.
This is what I have so far:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript - Unit 2 Summary</title>
<link href="unit2-summary.css" rel="stylesheet" type="text/css"></link>
<script type="text/javascript">
/*function swap()
{
var left = $('#leftWrapper').html();
var right = $('#rightWrapper').html();
$('#leftwrapper').html(left);
$('#rightWrapper').html(right);
return false;
}*/
function doClear()
{
document.computerForm.totalSystemPrice.value = "";
document.ComputerForm.yourName.value = "";
document.ComputerForm.yourAddress.value = "";
document.ComputerForm.yourAddress2.value = "";
document.ComputerForm.yourCityStateZip.value = "";
document.ComputerForm.yourPhone.value = "";
document.ComputerForm.yourEmail.value = "";
document.ComputerForm.computerCase[0].checked = false;
document.ComputerForm.computerCase[1].checked = false;
document.ComputerForm.computerCase[2].checked = false;
document.ComputerForm.computerMonitor[0].checked = false;
document.ComputerForm.computerMonitor[1].checked = false;
document.ComputerForm.computerMonitor[2].checked = false;
document.ComputerForm.computerPrinter[0].checked = false;
document.ComputerForm.computerPrinter[1].checked = false;
document.ComputerForm.computerPrinter[2].checked = false;
return;
}
function doSubmit()
{
if (validateText() == false)
{
alert("Required Data Missing - Please Complete");
return;
}
if (validateRadio() == false)
{
alert("Required Order Data Missing - Please Complete");
return;
}
alert("Your Order has been placed.");
return;
}
function validateText()
{
var yourName = document.ComputerForm.yourName.value;
if (yourName.length == 0) return false;
var yourAddress = document.computerForm.yourAddress.value;
if (yourAddress.length == 0) return false;
var yourCityStateZip = document.ComputerForm.yourCityStateZip.value;
if (yourCityStateZip.length == 0) return false;
var yourPhone = document.ComputerForm.yourPhone.value;
if (yourPhone == 0) return false;
var yourEmail = document.ComputerForm.yourEmail.value;
if (yourEmail == 0) return false;
return true;
}
function validateRadio()
{
if (document.ComputerForm.computerCase[0].checked) return true;
if (document.ComputerForm.computerCase[1].checked) return true;
if (document.ComputerForm.computerCase[2].checked) return true;
if (document.ComputerForm.computerMonitor[0].checked) return true;
if (document.ComputerForm.computerMonitor[1].checked) return true;
if (document.ComputerForm.computerMonitor[2].checked) return true;
if (document.ComputerForm.computerPrinter[0].checked) return true;
if (document.ComputerForm.computerPrinter[1].checked) return true;
if (document.ComputerForm.computerPrinter[2].checked) return true;
}
function getTotal()
{
var computerPrice()
document.getElementById('totalPrice').value.innerHTML = "Total Computer Price $"
}
function startup()
{
var imgArray = new Array(3);
var index = 0;
imgArray[0] = new Image;
imgArray[0].src = "ComputerCase.jpg";
imgArray[1] = new Image;
imgArray[1].src = "ComputerMonitor.jpg";
imgArray[2] = new Image;
imgArray[2].src = "ComputerPrinter.jpg";
return;
}
</script>
</head>
<body>
<form name="ComputerForm">
<h1 align="center">Comupter System Order Form</h1>
<div id="container" font="courier" size="10">
<div id="left"><div id ="leftWrapper" class="wrapper">
<p><p></p>
<div class="gallery">
<a target="_blank" href="ComputerCase.jpg">
<img src="ComputerCase.jpg">
</a>
</div>
<h4>Computer Case Style:</h4>
<input name="computerCase" type="radio" onClick="calculateTotal()" />Desktop Case ($500.00)<br />
<input name="computerCase" type="radio" onClick="calculateTotal()" />Mini-Tower Case ($600.00)<br />
<input name="computerCase" type="radio" onClick="calculateTotal()" />Full Tower Case ($700.00)<br />
<p></p>
<div class="gallery">
<a target="_blank" href="ComputerMonitor.jpg">
<img src="ComputerMonitor.jpg">
</a>
</div>
<h4>Computer Monitors</h4>
<input name="computerMonitor" type="radio" onClick="calculateTotal()" />17" LCD Flat Screen ($250.00)<br />
<input name="computerMonitor" type="radio" onClick="calculateTotal()" />19" LCD Flat Screen ($300.00)<br />
<input name="computerMonitor" type="radio" onClick="calculateTotal()" />21" LCD Flat Screen ($350.00)<br />
<p></p>
<div class="gallery">
<a target="_blank" href="ComputerPrinter.jpg">
<img src="ComputerPrinter.jpg"></a>
</a>
</div>
<h4>Computer Printers</h4>
<input name="computerPrinter" type="radio" onClick="calculateTotal()" />Inkjet Printer ($100.00)<br />
<input name="computerPrinter" type="radio" onClick="calculateTotal()" />Laser Printer ($250.00)<br />
<input name="computerPrinter" type="radio" onClick="calculateTotal()" />Color Laser Printer ($350.00)<br />
</p><p></p>
</div>
</div>
<div id="right"><div id="rightWrapper" class="wrapper">
<br><br>
<p>Total System Price: $
<input name="totalSystemPrice" size="14px" type="text" id="totalPrice" class="totalPrice" readonly>
</p>
<br><br>
<hr />
<p></p><p></p><p></p>
Name: <input name="yourName" size="50" type="text"><br />
Address: <input name="yourAddress" size="50" type="text"><br />
<input name="yourAddress2" size="50" type="text"><br />
City, State, Zip: <input name="yourCityStateZip" size="50" type="text"><br />
Phone Number: <input name="yourPhone" size="50" type="text"><br />
Email Address: <input name="yourEmail" size="50" type="text"></p>
</p>
<hr />
<br><br><br>
<div align="center">
<input type="button" id="submit" value="Submit Order" onClick="doSubmit()">
<input type="button" id="reset" value="Clear Values" onClick="doClear()">
</div>
<br />
</div></div>
</form>
</body>
</html>
The CSS page is so far:
body
{
color:black;
}
p
{
color:black;
font-size:12px;
font-family: Constantia, Aldhabi, Book Antiqua;
}
h1
{
color:blue;
font-weight:bold;
font-family:"Book Antiqua";
}
h4
{
color:blue;
font-weight:bold;
font-family:"Book Antiqua", Arial;
}
.gallery
{
float:right;
}
div.gallery.hover
{
border: 1px solid orange;
}
div.gallery.img
{
width:110px;
height: 110px;
}
#TotalSystemPrice
{
}
#container
{
display: table;
table-layout: fixed;
width:90%;
height:100%;
border: 1px solid black;
padding: 3px;
}
#left, #right
{
display: table-cell;
}
#left
{
width: 50%;
height: 100%;
background: white;
border: 1px solid blue;
margin:3px 2px;
}
#right
{
width: 50%;
height: 100%;
background-color:ivory;
border: 1px solid blue;
margin: 3px 2px;
}
#computerOrders
{
width:50%;
height:100%;
background-color:white;
}
#orderInfo
{
width:50%;
height:100%;
background-color:white;
}

Javascript quiz not going on to next quiz item

I have a quiz that should move on to the next question once you select an answer but at the moment my code doesn't work and it allows the user to select multiple answers, without anything happening afterwards.
Once they finish the last question their result should be displayed to them.
document.getElementById("beginquiz").addEventListener("click", startQuiz);
function startQuiz() {
document.getElementById("intro").style.display = "none";
document.getElementById("q1").style.display = "block";
}
var answerData = {
"p": 0,
"vp_w": 0,
"vp_e": 0,
"vp_a": 0,
"vp_s": 0
};
var buttons = document.querySelectorAll(".button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].onclick = buttonClicked;
}
function buttonClicked(buttonNext) {
var target = answer.target; //1. 'this' is parent, need target
console.log(target);
//get the current element's data-score value
var selectedType = target.dataset.score; //2. score is the value
//increase the selected answer's 'type' by 1
console.log(selectedType);
answerData[selectedType]++;
//Hide the current question div
this.parentElement.style.display = "none";
//Work out what the next question div is
var nextQuestion = this.parentElement.dataset.next;
//Display the next question element
console.log(nextQuestion);
document.getElementById(nextQuestion).style.display = "block";
if(document.getElementById(nextQuestion))
document.getElementById(nextQuestion).style.display = "block";
else
printResult();
}
function calculateResult (answerData){
var highest = Math.max(total_points.p, total_points.vp_s, total_points.vp_e, total_points.vp_w, total_points.vp_a);
var result;
for (var i in total_points) {
if (total_points.hasOwnProperty(i)){
if (total_points[i] === highest){
result = i;
}
}
}
switch(result) {
case 'p':
result = 'President';
break;
case 'vp_w':
result = 'Vice-President Welfare';
break;
case 'vp_e':
result = 'Vice-President Education';
break;
case 'vp_s':
result = 'Vice-President Sports';
break;
case 'vp_a':
result = 'Vice-President Activities';
break;
default:
break;
}
return result;
};
function printResult() {
document.getElementById('result').innerHTML = '<h2>You are: '+result+'</h2>';
}
.question,
#result {
display: none;
}
.button li {
border: 1px solid;
border-radius: 3px;
background-color: #eee;
text-align: center;
line-height: 2em;
padding: 0.5em;
margin: 0.5em;
width: 80%;
margin: 0 auto;
}
.button li:hover {
color: #bfbfbf;
background-color: #555;
}
#intro,
.question,
#result {
max-width: 600px;
margin: 0 auto;
}
#beginquiz {
border: 1px solid;
border-radius: 3px;
background-color: #eee;
text-align: center;
line-height: 2em;
padding: 0.5em;
margin: 0.5em;
width: 20em;
margin: 0 auto;
}
#beginquiz:hover {
color: #bfbfbf;
background-color: #555;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="intro">
<button id="beginquiz">Start the quiz</button>
</div>
<form name="quiz" method="post" name="buttons" id="quiz" onsubmit="return false">
<div class="question" id="q1" data-next="q2">
<li><div>What is?</div></li>
<input id="answer" type="radio" data-score="p">Answer 1<br>
<input id="answer" type="radio" data-score="vp_a">Answer 2<br>
<input id="answer" type="radio" data-score="vp_s">Answer 3<br>
<input id="answer" type="radio" data-score="vp_w">Answer 4<br>
<input id="answer" type="radio" data-score="vp_e">Answer 5<hr>
</div>
<div class="question" id="q2" data-next="q3">
<li><div>What is?</div></li>
<input id="answer" type="radio" data-score="p">Answer 1<br>
<input id="answer" type="radio" data-score="vp_a">Answer 2<br>
<input id="answer" type="radio" data-score="vp_s">Answer 3<br>
<input id="answer" type="radio" data-score="vp_w">Answer 4<br>
<input id="answer" type="radio" data-score="vp_e">Answer 5<hr>
</div>
<div class="question" id="q3" data-next="q4">
<li><div id="q3" data-next="q4">What is?</div></li>
<input id="answer" type="radio" data-score="p">Answer 1<br>
<input id="answer" type="radio" data-score="vp_a">Answer 2<br>
<input id="answer" type="radio" data-score="vp_s">Answer 3<br>
<input id="answer" type="radio" data-score="vp_w">Answer 4<br>
<input id="answer" type="radio" data-score="vp_e">Answer 5<hr>
</div>
<div class="question" id="q4">
<li><div>What is?</div></li>
<input id="answer" type="radio" data-score="p">Answer 1<br>
<input id="answer" type="radio" data-score="vp_a">Answer 2<br>
<input id="answer" type="radio" data-score="vp_s">Answer 3<br>
<input id="answer" type="radio" data-score="vp_w">Answer 4<br>
<input id="answer" type="radio" data-score="vp_e">Answer 5<hr>
</div>
</form>
<div id="result">
<h2>You are:</h2>
</div>
In your buttonclicked function you had some errors on how you were getting the elements. Here is the updated function. There was another error in the printResults that there was no call to display the results div. You also are not calling the calulateResults functions.
function buttonClicked(buttonNext) {
//var target = answer.target; //1. 'this' is parent, need target
var target;
for(i=answer.length-1;i>=0;i--){
if(answer[i].checked == true){
target = answer[i];
break;
}
}
console.log(target);
//get the current element's data-score value
var selectedType = target.dataset.score; //2. score is the value
//increase the selected answer's 'type' by 1
console.log(selectedType);
answerData[selectedType]++;
//Hide the current question div
console.log(target.parentElement.id);
//this.parentElement.style.display = "none";
target.parentElement.style.display = "none"
//Work out what the next question div is
var nextQuestion = target.parentElement.dataset.next;
//Display the next question element
console.log(nextQuestion);
//document.getElementById(nextQuestion).style.display = "block";
if(document.getElementById(nextQuestion))
document.getElementById(nextQuestion).style.display = "block";
else
printResult();
}
You needed to use a for loop to get the target answer in the array of answers. I decremented the loop to get the last answered question. The other change is to how you got the parent ID. With this.parentElement it was coming back with the body due to the this element was focused on the form, the element the clcik event was fired on. The last thing I commented out the extra document.getElementById(nextQuestion).style.display = "block"; before the check.

Categories