Javascript quiz: radio button score validation - javascript

I'm learning javascript, and for a class assignment I'm working on a simple quiz. Found here: http://redwood.colorado.edu/scho5922/dm2/projects/project1.html
My problem is that I can't get the radio buttons to validate correctly. This prevents the quiz score from being calculated. When you click enter it cycles through the questions, but choosing the correct answer doesn't increase the score. I've tested this by adding both an alert after the if statement and a button that displays the 'score' variable. There is no alert with the correct answer and the score button (not on current version) displays a score of 0.
JavaScript
<script>
var beers =[
["New World Porter", "Avery"],
["Ellie's Brown Ale","Avery"] ,
["Out of Bounds Stout","Avery"] ,
["Hazed & Infused Dry Hopped Ale", "Boulder Beer"],
["Sweaty Betty Blonde Ale", "Boulder Beer"],
["Mojo IPA", "Boulder Beer"],
["Mama's Little Yellow Pils", "Oskar Blues"],
["Dale's Pale Ale", "Oskar Blues"],
["G'Knight Imperial Red Ale","Oskar Blues"],
["Old Chub Scotch Ale","Oskar Blues"]
] ;
var score = 0;
var questionNum = 0;
var turns = 0;
function enterF (beer){
questionNum++;
turns++;
var question = "What brewery makes ";
document.getElementById("header").innerHTML= question + beers[questionNum][0];
var answer = document.getElementsByName("beerbut").value.checked;
if(answers[i].checked == beers[questionNum-1][1]){
score++;
alert(score);
}
}
</script>
HTML
<body onload="popup()">
<h1 id="header">What brewery makes New World Porter</h1>
<div class="buttons">
<form>
<label for="_avery"> Avery</label>
<input type="radio" name="beerbut" id="_avery" value="Avery">
<br><br>
<label for="_bb"> Boulder Beer</label>
<input type="radio" name="beerbut" id="_bb" value="Boulder Beer">
<br><br>
<label for="_oskar"> Oskar Blues</label>
<input type="radio" name="beerbut" id="_oskar" value="Oskar Blues">
<br><br>
<label for="lefthand"> Left Hand </label>
<input type="radio" name="beerbut" id="_lefthand" value="Left Hand">
<br><br>
<input type="button" name="enter" id="enterbut" value="enter" onClick="enterF()">
</form>
</div>
</body>
</html>

You're trying to get a value from multiple elements at the same time. That's not how you do it.
Change this in the javascript
var answer = document.getElementsByName("beerbut").value.checked;
For something like this
var elements = document.getElementsByName("beerbut");
for(i = 0; i < elements.length; i++){
if(elements[i].checked){
alert(elements[i].value);
}
}

Related

I get NaN error when trying to create a basic calculator

I'm 3 days into learning Javascript and im really excited to understand more of this language, before i started i've done a basic HTML & CSS education. I'm currently on a 2 year program in a University in Sweden.
I'm trying to create a very basic calculator, that for now only adds 2 numbers together. I have 1 box, and another box. I want to make that each number written in each of these boxes is displayed as the total of box1, box2 in the third and final box.
At this moment i get "NaN" in the 3rd box when trying to add 2+3.
As i said, I'm really new and i appreciate all help i can get, and note that im not here for anyone to do my assignments which we have plenty of, i am really interessted in learning and understanding the language because i would like to work with this later in life when im done with my education.
Cheers!
<h1>Addera två tal med varandra</h1>
<form>
<input type="text" value="0" id="tal1" /> <br>
<input type="text" value="0" id="tal2" /> <br>
<input type="button" value="Beräkna" onClick="kalkylera();" />
<p>Den totala summan är</p>
<input type="text" value="0" id="svar" />
</form>
<script>
function kalkylera() {
//Get the two numbers entered in the box
var ForstaTalet = document.getElementById("tal1").value;
var AndraTalet = document.getElementById("tal2").value;
//Count the two entered numbers together
var svar = tal1 + tal2;
//Show result
document.getElementById("svar").value = svar;
}
</script>
PS, I'm not sure why "//# sourceURL=pen.js" is written i the bottom of the calculator when adding this to the codepen, that is not how it looks when viewing it in chrome.
Thanks in advance.
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Calculator</title>
</head>
<body>
<form>
<input type="text" placeholder='num1' id="tal1"/> <br>
<input type="text" placeholder='num2' id="tal2"/> <br>
<input type="button" value="Add" onClick="sum()"/>
<input type="text" placeholder='sum' id="svar"/>
</form>
<script>
function sum()
{
var ForstaTalet = parseFloat(document.getElementById("tal1").value);
var AndraTalet = parseFloat(document.getElementById("tal2").value);
var svar = ForstaTalet + AndraTalet;
document.getElementById("svar").value = svar;
}
</script>
</body>
</html>
This works fine.
You need to cast your values as float with parseFloat and use the right variables as in the following example:
//Get the two numbers entered in the box
var ForstaTalet = parseFloat(document.getElementById("tal1").value);
var AndraTalet = parseFloat(document.getElementById("tal2").value);
//Count the two entered numbers together
var svar = ForstaTalet + AndraTalet;
//Show result
document.getElementById("svar").value = svar;

Creating a simple mathematics game

I am new to the javascript developing world and I took it upon myself to create a small game that my fathers students will be able to play at school. This game consists of 4 different mathematical operations (Adding,Subtracting,Multiplication,Division). Once the student clicks on the operation button, they will then be transferred to a new page. This page will have numbers from 1 to 10. This number will be used as a static number. After the user selects this number, they will have 10 different problems to answer. The first number will be a random number from 1 to 12 and the second number will be the digit they selected on the page before. After completing the 10 problems, they will be greeted with a page that will inform them which questions they have missed. I have started the code for the addition part but I ran into several complications.
1) how do i transfer the answer from one function, to another? This will be used to check the input.
2) Will it be more intuitive to use a switch statement in order to select the operation & the static number?
3) Is there any other methods that would facilitate the making of this game?
I would like to thank you in advance and apologize for the long post. I am a bit lost and would love to get some kind of feedback.
var x;
function startAdd() {
var random = new Array();
for (var i = 0; i < 1; i++) {
random.push(Math.floor(Math.random() * 13));
// console.log(random[i]);
}
var allRadioButtons = document.getElementsByName("dif");
var secondNumber;
for (var i in allRadioButtons) {
if (allRadioButtons[i].checked) {
secondNumber = +allRadioButtons[i].value;
break;
}
}
for (var a = 0; a < 1; a++) {
document.getElementById('probFirst').innerHTML = random[a];
document.getElementById('probSecond').innerHTML = secondNumber;
/*
compareUser();
function compareUser(){
if (prob != )
} */
}
}
function myFunction() {
var x = document.getElementById("userNumb").value;
document.getElementById("Answer").innerHTML = x;
}
<title>RicoMath - Addition</title>
<body>
<h1>RicoMath</h1>
<h1 class="add">Addition</h1>
<h2>Difficulty</h2>
<div id="options">
<div>
<input id="num1" type="radio" name="dif" value="1">
<label for="num1">1</label>
</div>
<div>
<input id="num2" type="radio" name="dif" value="2">
<label for="num2">2</label>
</div>
<div>
<input id="num3" type="radio" name="dif" value="3" checked>
<label for="num3">3</label>
</div>
<div>
<input id="num4" type="radio" name="dif" value="4">
<label for="num4">4</label>
</div>
<div>
<input id="num5" type="radio" name="dif" value="5">
<label for="num5">5</label>
</div>
<button onclick="startAdd()">Begin!!!!</button>
<h4 id='probFirst'></h4>
<h4 id='probSecond'></h4>
</div>
<input type="number" id="userNumb" value="">
<button onclick='myFunction()'>Enter UserNumb</button>
<p id="Answer"></p>
</body>
1) To transfer the data to your next "page", the easy option for you would be to have seperate divs for seperate pages in the same html file. Then when you need to go the the "next page", just show the div you need to show and hide the others.
Here's a the html + pure javascript code for that with a working example:
<body>
<div id="page1" style="border-width:2px;border-style:solid">
your first page
<button onclick="showPage2()">Go to Page 2</button>
</div>
<div id="page2" style="border-width:2px;border-style:solid">
2nd page
</div>
<div id="page3">
3rd page
</div>
<script>
showPage1();
function hide(id){
document.getElementById(id).hidden = true;
}
function show(id){
document.getElementById(id).hidden = false;
}
function showPage1(){
show("page1");
hide("page2");
hide("page3");
}
function showPage2(){
show("page2");
hide("page1");
hide("page3");
}
</script>
</body>
Here's a working fiddle.
To transfer your value from the input, just use document.getElementById() since you are in the same html document.
2) To get the selected value from the radio button list, just use (as per your code):
var rates = document.getElementById('options').value;
You can use the same method to get the value from a input box. Please make sure you add a check for empty input and also to check if a radio button has been selected before getting the value.
I don't see any need to loop as you have done.
3) Definitely learn and use jquery. It will make your effort much less.
Hope this helps and happy coding!

Javascript: Displaying output dependent on which checkedboxes pressed?

I am creating a web app that will take 2 sets of user input, i.e. Age and Weight and display an outcome dependent on what box is ticked on each.
What is the best way to do this?
I.e. if one age and weight is selected I wish to display one value, but if a different combo is selected I wish to display another?
I ask this as I know it can be done using multiple if statements, but I assume there is a better way.
Current Code:
<!DOCTYPE html>
<html>
<body>
<h1>Health Calculator</h1>
<p>Select age</p>
<form action="age.asp" method="get">
<input type="checkbox" name="Age" value="under25"> Under 25<br>
<input type="checkbox" name="Age" value="over25"> Over 25<br>
</form>
<p>Select Weight</p>
<form action="weight.asp" method="get">
<input type="checkbox" name="Probability" value="under80"> Under 80kg<br>
<input type="checkbox" name="Probability" value="over80"> Over 80kg<br>
</form>
<br>
<button onclick= "analyseHealth"> Analyse health </button> <br>
<script>
function analyseHealth(age, weight){
//LOGIC RELATING TO CHECK BOXES
}
</script>
</body>
</html>
This is not finished but I think you can guess the rest.
http://codepen.io/anon/pen/RPpjBm
function analyseHealth()
{
var ages = document.getElementsByName('Age');
var probs = document.getElementsByName('Probability');
var age = undefined;
for(var i = 0; i < ages.length; i++)
{
if(ages[i].checked)
{
age = ages[i].value;
}
}
var probability = undefined;
for(var i = 0; i < probs.length; i++)
{
if(probs[i].checked)
{
probability = probs[i].value;
}
}
switch(age){
case 'under80': break;
}
}
Better than if might be switch. First you get the checked radio buttons which might be the better choice here.

How to render text from javascript object in HTML form

I have an array containing two objects:
var questions = [{question: "Is the sky blue?", choices: ["Yes", "No"], correctAnswer:0},{question: "Is water wet?", choices: ["Yes", "No"], correctAnswer:0}]
I have some javascript to make the questions render on the screen with HTML:
<script>
function askQuestion(x){
var questiontest = document.getElementById('question');
questiontest.innerHTML = x.question;
}
function loop(){
for(i = 0; i < questions.length; i++){
askQuestion(questions[i]);
}
}
left some stuff out here, not that relevant to question
addEventListener('load',loop);
</script>
My HTML looks like this, displays the current question but not the text of the choices found in the questions object:
<label for="choice" id="question"></label>
<br><input type="radio" id="choice_1" name="choice" value="1"></input>
<br><input type="radio" id="choice_2" name="choice" value="2"></input>
Using this code I can render the question and then two radio buttons i.e. without the text of the choices. Is there anyway that I can render the text of the choices from the questions object next to the radion buttons? or do I have to do something stupid like this to make it render correctly?
<br><input type="radio" name="choice" value="1"><p id="choice_1"></p></input>
I'm trying to do it with vanilla javascript at the moment and will research doing in with jQuery shortly.
Thanks any help appreciated!
Re-structure your HTML so you can label the inputs individually, then it becomes easy
HTML
<form id="qform" action="">
<fieldset>
<legend id="l0"></legend>
<label id="l1" for="c1"></label>
<input id="c1" type="radio" name="choice" value="1" />
<br />
<label id="l2" for="c2"></label>
<input id="c2" type="radio" name="choice" value="2" />
</fieldset>
</form>
JavaScript
function questionFactory() {
var i = 0,
l0 = document.getElementById('l0'),
l1 = document.getElementById('l1'),
l2 = document.getElementById('l2');
return function askQuestion() {
if (i >= questions.length) return false;
l0.textContent = questions[i].question;
l1.selected = false;
l1.textContent = questions[i].choices[0];
l2.selected = false;
l2.textContent = questions[i].choices[1];
++i;
return true;
}
}
var ask = questionFactory();
ask(); // asks q1, returns true
ask(); // asks q2, returns true
ask(); // returns false, there were no more questions to ask
DEMO

How to dynamically add text fields to a form based on a number the user puts in

I'm attempting to make a form that asks the user for a number of units, then asks whether or not they would like those units to be provisioned, and depending on the answer, generates text fields corresponding with the number of units the typed in, along with a text field asking for an account number.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">
</script>
<script type="text/javascript">
function Getunits(value) {
var units = document.getElementById('units');
for(count=0; count<=units; count++) {
$("<input type='text'>").appendTo("inpane");
}
document.getElementByTag('futureacc').InnerHTML='What is your account number? <input type="text" value="accountnum">';
}
</script>
</head>
<body>
<div id="container">
<form method="post" action="sendcontact.php">
<div id="unitammount" class="inpane">
Number of units ordered: <input type="text" name="units" id="units"/><br />
</div>
<div id="futureacc" class="inpane">
Are these units to be provisioned? <input type="radio" name="select" value="yes" onClick="Getunits('units.value')"/> Yes <input type="radio" name="select" value="no"/> No
</div>
Obviously I would like the new text fields to appear inside the futureacc div and inpane div respectively.
I don't know whether it's the loop that doesn't do anything or that I'm not appending correctly but as I currently have it this does nothing...
Any help would be greatly appreciated.
You had a number of errors with your code. It was confusing because you were mixing jQuery and pure Javascript. It's generally better to just use jQuery if you've decided to use it anyway. Your loop should have been iterating while it was smaller than units.val(), not while it was smaller than or equal to units. innerHTML is spelled with a lowercase "i," and your appendTo selector needed a period before the class name. I went ahead and cleaned up your code so it should work now!
HTML:
<div id="container">
<form method="post" action="sendcontact.php">
<div id="unitammount" class="inpane">
Number of units ordered: <input type="text" name="units" id="units"/>
</div><br>
<div id="futureacc" class="inpane">
Are these units to be provisioned? <input type="radio" name="select" value="yes" onClick="getUnits()"/> Yes <input type="radio" name="select" value="no"/> No <br>
</div>
</form>
</div>​
Javascript:
function getUnits() {
var units = $("#units").val();
for (var count = 0; count < units; count++) {
$("<input type='text' /><br>").appendTo("#futureacc");
}
$("#futureacc").append('<br>What is your account number? <input type="text" placeholder="accountnum">');
}​
WORKING DEMO
var units = document.getElementById('units');
needs to be
var units = document.getElementById('units').value;
you are passing value to onclick but it is a string will not give you exact value anyway you are not using it in you function so it doesnt have any side effect.
also you need to some error check to make sure that user has entered a number
with
for(count=0; count<=units; count++)
You are adding 1 more text box than user entered value. so if user has entered 4 you are creating 5 <= should be changed to <
This is wrong
onClick="Getunits('units.value')"
Instead use this:
onClick="Getunits(units.value)"
try this
$(document).ready(function(){
$('input[name=select]').click(function(){
if($(this).val() ==='yes'){
var numberOfTextboxes = $('#units').val();
for(var i =0; i<numberOfTextboxes; i++){
$('#unitammount').append('<input type="text" />');
}
}
});
});
See the fiddle

Categories