Javascript: Displaying output dependent on which checkedboxes pressed? - javascript

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.

Related

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 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

Javascript Radio / Checkbox Problems

I have this simple script. I'm trying to get the checked values and add them to a running total that's in the diabled input box. I know it's getting checked option but it's not updating to the input box and I'm not sure why. Can anyone help me?
<html>
<head>
<script type="text/javascript">
function updateForm()
{
var type = document.pizzaForm.pizzaType;
var toppings = document.pizzaForm.toppings;
var pizzaType;
var toppings;
for(var i = 0; i <= type.length; i++)
{
if(type[i].checked)
{
total = type[i].value;
}
}
for(var i = 0; i <= toppings.length; i++)
{
if(toppings[i].checked)
{
toppings += toppings[i].value;
}
}
var total = pizzaType + toppings;
pizzaForm.total.value = total;
}
</script>
</head>
<body>
<h1>Order Pizza Here:</h1>
<form action="" method="get" name="pizzaForm">
What Type of Pizza Would You Like? <br />
<input type="radio" name="pizzaType" value="10.00" onchange="updateForm()" />Vegetarian<br />
<input type="radio" name="pizzaType" value="20.00" onchange="updateForm()" />Meat Lovers<br />
<br />
<br />
Extra Toppings: <br />
<input type="checkbox" name="toppings" value="2.00" onchange="updateForm()" />Extra Cheese <br />
<input type="checkbox" name="toppings" value="3.00" onchange="updateForm()" />Mushrooms <br />
<input type="checkbox" name="toppings" value="4.00" onchange="updateForm()" />Anchovies <br />
<br />
Total <input type="text" disabled="disabled" name="total" />
</form>
</body>
</html>
You have a few basic Javascript errors:
your for loops look like:
for(var i = 0; i <= type.length; i++)
this means they will go from 0 to length (including length) = length + 1
It should be:
for(var i = 0; i < type.length; i++)
see the diffference? <= is now <. (off by one error?)
you are using toppings variable twice. (javascript is really bad with this and lets you shoot yourself in the foot.) Also you should be initialisng all values.
var type = document.pizzaForm.pizzaType;
var toppings = document.pizzaForm.toppings;
var pizzaTypeValue = 0;
var toppingsValue = 0;
I've also added Value to the variables that hold numbers rather than elements. Other might prefix this or some such convention to remember it holds a value not a list of elements.
the values in markup are strings use parseFloat( to turn them into floats:
pizzaTypeValue += parseFloat(type[i].value);
also note the += means: add this to me. Equivalent to pizzaTypeValue = pizzaTypeValue + ....
there is no real need for the total variable. just add a comment if you want to remember it is the total.
See this jsFiddle: http://jsfiddle.net/F53ae/ to see it in action.
Here is the working code. I put it in jsfiddle for you. The main problem was that you had two variables named toppings. Also, in the first loop, you were setting the "total" variable, when you meant to set the other total. Check it out.
http://jsfiddle.net/eXPAj/1/

Trying to find selected radio button. What's wrong?

I can read out text field values, but when I try to find the selected radio button, I get nothing.
$(document).ready(function(){
$("form#create_form").submit(function() {
var title = $('#title').attr('value');
var owner = $('#owner').attr('value');
var users = $('#users').attr('value');
var groups = $('#groups').attr('value');
var begin_date = $('#begin_date').attr('value');
var end_date = $('#end_date').attr('value');
// get selected radio button
var type = '';
for (i=0; i<document.forms[0].type.length; i++) {
if (document.forms[0].type[i].checked) {
type = document.forms[0].type[i].value;
}
}
HTML:
<div class="create-new">
<form id="create_form" name="create_form" action="" method="post">
...
<input name="type" id="type" value="individuel" type="radio" /> Individuel <br/>
<input name="type" id="type" value="course" type="radio" /> Course <br/>
<button class="n" type="submit">Create</button>
</form>
What am I doing wrong?
I would suggest an alternative method to getting the selected radio button (since you are already using jQuery):
$('input:radio[name=type]:checked').val();
This solution is an example on .val().
The above solution is much more succinct, and you avoid any conflicts in the future if other forms are added (i.e you can avoid the potentially hazardous document.forms[0]).
Update
I tested your original function with the following fiddle and it works:
http://jsfiddle.net/nujh2/
The only change I made was adding a var in front of the loop variable i.

Categories