Creating a simple mathematics game - javascript

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!

Related

HTML Quiz Multiple Form Submission via Email

I have created a quiz using HTML currently there are 5 questions in total and I have it coded so that only the question being answered appears so users taking the quiz cannot see upcoming questions. The way I have done it using multiple forms so for each question there is a separate form this makes it a pain to be able to send all of the answers to the questions via email, currently it only sends the last questions... Is there a way I can combine my forms into one big form or possibly have a button that submits all my forms?
Any help would be greatly appreciated :)
Currently, it won't let me send code. I'll try again.
Hi and welcome to Stackoverflow!
If I understood correctly, you can split the form in sections like the following:
<form POST="..." onsubmit="onNextStep">
<div class='form-section' id='question-1'>
<!-- code here -->
</div>
<div class='form-section' id='question-2'>
<!-- code here -->
</div>
<div class='form-section' id='question-3'>
<!-- code here -->
</div>
<div class="form-footer">
<button type="submit"> Next </button>
</div>
</form>
and then add an event on button click that increments the current step (0, 1, 2...) and hide all the divs without the correct id and then submit the form when on the final step.
let totalSteps = 3;
let step = 1;
function onNextStep(e) {
const currentStep = step;
const nextStep = step + 1;
// in the last step change the button text
if ( nextStep == totalSteps ) {
document.querySelector('form button[type="submit"]').innerText = "Submit"
}
// If the last step is completed, submit the form.
if ( nextStep > totalSteps ) {
return
}
// prevent form submission
e.preventDefault()
// hide the current section
document.getElementById('question-'+nextStep).style.display = 'block'
// show the next section
document.getElementById('question-'+curentStep).style.display = 'none'
// increment our steps counter
step += 1
}
This example with some adjustments should fit your case.
Just use the one form.
Use the fieldset tag to encapsulate your questions then use javascript to hide and show as needed.
let questions = document.querySelectorAll(".question");
let answerButtons = document.querySelectorAll(".question button");
for (var i = 0; i < answerButtons.length; i++) {
answerButtons[i].addEventListener("click",function() {
//Get Closest question
var question = this.closest(".question");
//Remove Active class
question.classList.remove("active");
//Add active class to next sibling
question.nextElementSibling.classList.add("active");
});
}
.question:not(.active) {
display: none;
}
<form action="">
<fieldset class="question active">
<legend>Question 1 of 3</legend>
<label>What is your name? <input type="text" name="qName"></label>
<button type="button">Submit Answer</button>
</fieldset>
<fieldset class="question">
<legend>Question 2 of 3</legend>
<label>What is your quest? <input type="text" name="qQuest"></label>
<button type="button">Submit Answer</button>
</fieldset>
<fieldset class="question">
<legend>Question 3 of 3</legend>
<label>What is your quest? <input type="text" name="qName"></label>
<button type="submit">Submit Quiz</button>
</fieldset>
</form>

How can I set default and change price with checkboxes?

I am trying to create an interface of a website which has a varying price dependent on whether check boxes are checked and which has a default value if none are selected.
The varying value is in a table which has the id 'Level1Price' which I want to default to a value of '£5.11' if neither of the two check boxes are checked and the value to chage if either one or both are selected and where the two chekc boxes on their own would hold a different value each.
The two check boxes have the id's 'partner' and 'children'. When no checkboxes are checked (for the purpose of this demonstartion) the value of 'Level1Price in the table should be 5.
If just the 'partner' checkbox is checked the value of 'Level1Price' is 10.
If just the 'children' checkbox is checked the value of 'Level1Price' is 12.
If both checkboxes are checked the value of 'Level1Price' is 20.
var partner = document.getElementById("partner");
var children = document.getElementById("children");
function calc()
if (!partner.checked && !children.checked)
{
document.getElementById('Level1Price')element.innerHTML = 5;
} else if (partner.checked && !children.checked)
{
document.getElementById('Level1Price')element.innerHTML = 10;
} else if (!partner.checked && children.checked)
{
document.getElementById('Level1Price')element.innerHTML = 12;
} else if (partner.checked && children.checked)
{
document.getElementById('Level1Price')element.innerHTML = 20;
}
This is the code that I thought would work and i'm struggling. I apologies if I have made rookie mistakes i'm quite new to this and couldn't find any working resolutions anywhere.
Thanks in advance.
These are the chekcboxes that I want to help change the vale in the table.
<div class="addition">
<label for="partner">+ Partner:</label>
<input type="checkbox" name="partner" id="partner" value="partner" required>
</div>
<div class="addition">
<label for="children">+ Children:</label>
<input type="checkbox" name="children" id="children" value="children" required>
</div>
</div>
This is the Table data I want to be able to populate
<tr>
<td scope=col id="Level1Price" value="5.11"> <b></b> <br/> per month</td>
<td scope=col id="Level2Price" value="9.97"> <b></b> <br/> per month</td>
<td scope=col id="Level3Price" value="14.06"> <b></b> <br/> per month</td>
</tr>
Is it possible to automatically update without the need for a 'calculate' button?
Provided your HTML looks like:
<span id="Level1Price"></span>
then:
document.getElementById('Level1Price').innerHTML = 20;
will result in your HTML being:
<span id="Level1Price">20</span>
Basically you just have a syntax problem (remove the erroneous 'element' text).
There is a small syntax error in your code. for better understanding, I have attached a fully functional code to meet your requirement.
Kindly refer the following code.
var partner = document.getElementById("partner");
var children = document.getElementById("children");
function calc() {
var val = 5;
if (partner.checked && !children.checked) {
val = 10;
} else if (!partner.checked && children.checked) {
val = 12;
} else if (partner.checked && children.checked) {
val = 20;
}
document.getElementById('Level1Price').innerHTML = val;
}
Partner: <input type="checkbox" id="partner" /> <br /> Children: <input type="checkbox" id="children" /> <br /> Level1 Price:
<span id="Level1Price"></span>
<br />
<button onClick="calc()">Calculate</button>
If still you find any issue or have any doubt feel free to comment, I will update my answer. TIA

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.

Javascript quiz: radio button score validation

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);
}
}

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