I'm having trouble with a project I am doing for university.
It consists on creating a diabetes risk assessment tool using html forms and javascript.
Basically there are 4 questions, each with 4 possible answers (using radio buttons, and user can only choose one answer per question).
In the end, there will be a "Calculate" button which will calculate the value of the selected answers, sum the values and display a message according the result. Here is the code for the html and javascript:
let calc = document.getElementById('form');
calc.addEventListener('submit', calculateAndPrintRisk);
function calculateRisk() {
let age = document.querySelector('input[name="age"]:checked').value;
let bmi = document.querySelector('input[name="bmi"]:checked').value;
let diabetes = document.querySelector('input[name="diabetes"]:checked').value;
let diet = document.querySelector('input[name="diet"]:checked').value;
return age + bmi + diabetes + diet;
};
function calculateAndPrintRisk(e) {
e.preventDefault();
var risk;
var riskTotal = calculateRisk();
if (riskTotal) {
if (riskTotal <= 15) {
alert("risk is low");
} else if (riskTotal <= 25) {
alert(risk = "medium");
} else {
alert(risk = "high");
}
}
}
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript FMA</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
</head>
<script src="diabetestool.js"> </script>
<body>
<div id="wrapper">
<h1>The Diabetes Risk Assesment Tool</h1>
<div id="Options">
<form id="form">
<p> How old are you? </p>
1-25 <input type="radio" name="age" value="0" checked> 26-40 <input type="radio" name="age" value="5"> 41-60 <input type="radio" name="age" value="8"> 60+ <input type="radio" name="age" value="10">
<p> What is your BMI? </p>
0-25 <input type="radio" name="bmi" value="0" checked> 26-30 <input type="radio" name="bmi" value="0"> 31-35 <input type="radio" name="bmi" value="9"> 35+ <input type="radio" name="bmi" value="10">
<p> Does anybody in your family have diabetes? </p>
No <input type="radio" name="diabetes" value="0" checked> Grandparent <input type="radio" name="diabetes" value="7"> Sibling <input type="radio" name="diabetes" value="15"> Parent <input type="radio" name="diabetes" value="15">
<p> How would you describe your diet? </p>
Low sugar <input type="radio" name="diet" value="0" checked> Normal sugar <input type="radio" name="diet" value="0"> Quite high sugar <input type="radio" name="diet" value="7"> High sugar <input type="radio" name="diet" value="10">
<input type="submit" id="calculate" name="button_calculate" value="Calculate">
</form>
</div>
</div>
</body>
</html>
The code shows no errors, but does not work when I hit Calculate.
Any help would be greatly apreciated, since I am still learning javaScript.
Following 2 statements must have thrown errors -
alert("risk is low";
alert(risk = "high";
Hit F12 while you execute your code on any browser. Look for console in it. You must be seeing errors there.
You don't call your function when you submit your form
You need to add and eventListener to detect when you submit your post, then cancel the Event, call your calcultateRisk function
Your event should be something like that.
document.getElementById('form1').addEventListener('submit', function(evt){
evt.preventDefault();
// do what you want
// call your function
})
You can not use same id for more than one HTML element.
I have updated the code and used querySelector to get the value of radio elements.
let calc = document.getElementById('form');
calc.addEventListener('submit', calculateAndPrintRisk);
function calculateRisk() {
let age = document.querySelector('input[name="age"]:checked').value;
let bmi = document.querySelector('input[name="bmi"]:checked').value;
let diabetes = document.querySelector('input[name="diabetes"]:checked').value;
let diet = document.querySelector('input[name="diet"]:checked').value;
return age + bmi + diabetes + diet;
};
function calculateAndPrintRisk(e) {
e.preventDefault();
var risk;
var riskTotal = calculateRisk();
if (riskTotal) {
if (riskTotal <= 15) {
alert("risk is low");
} else if (riskTotal <= 25) {
alert(risk = "medium");
} else {
alert(risk = "high");
}
}
}
<div id="wrapper">
<h1>The Diabetes Risk Assesment Tool</h1>
<div id="Options">
<form id="form">
<p> How old are you? </p>
1-25 <input type="radio" name="age" value="0" checked> 26-40 <input type="radio" name="age" value="5"> 41-60 <input type="radio" name="age" value="8"> 60+ <input type="radio" name="age" value="10">
<p> What is your BMI? </p>
0-25 <input type="radio" name="bmi" value="0" checked> 26-30 <input type="radio" name="bmi" value="0"> 31-35 <input type="radio" name="bmi" value="9"> 35+ <input type="radio" name="bmi" value="10">
<p> Does anybody in your family have diabetes? </p>
No <input type="radio" name="diabetes" value="0" checked> Grandparent <input type="radio" name="diabetes" value="7"> Sibling <input type="radio" name="diabetes" value="15"> Parent <input type="radio" name="diabetes" value="15">
<p> How would you describe your diet? </p>
Low sugar <input type="radio" name="diet" value="0" checked> Normal sugar <input type="radio" name="diet" value="0"> Quite high sugar <input type="radio" name="diet" value="7"> High sugar <input type="radio" name="diet" value="10">
<input type="submit" id="calculate" name="button_calculate" value="Calculate">
</form>
</div>
</div>
There are a few typos, an unneccessary form ( as you dont want to submit something) and input values are generally strings, which are concatenated through the + operator. You may want to get all checked ones:
[...document.querySelectorAll('input:checked')]
and reduce them to their summed up value:
.reduce((sum,el)=>sum+parseInt(el.value),0);
function calculateRisk() {
return [...document.querySelectorAll('input:checked')].reduce((sum, el) => sum + parseInt(el.value), 0);
}
function calculateAndPrintRisk() {
var riskTotal = calculateRisk();
if (riskTotal <= 15) {
alert("risk is low");
} else if (riskTotal <= 25) {
alert("risk is medium");
} else {
alert("risk is high");
}
}
<div id="wrapper">
<h1>The Diabetes Risk Assesment Tool</h1>
<div id="Options">
<p> How old are you? </p>
1-25 <input type="radio" id="opt" name="age" value="0" checked> 26-40 <input type="radio" id="opt" name="age" value="5"> 41-60 <input type="radio" id="opt" name="age" value="8"> 60+ <input type="radio" id="opt" name="age" value="10">
<p> What is your BMI? </p>
0-25 <input type="radio" id="opt" name="bmi" value="0" checked> 26-30 <input type="radio" id="opt" name="bmi" value="0"> 31-35 <input type="radio" id="opt" name="bmi" value="9"> 35+ <input type="radio" id="opt" name="bmi" value="10">
<p> Does anybody in your family have diabetes? </p>
No <input type="radio" id="opt" name="diabetes" value="0" checked> Grandparent <input type="radio" id="opt" name="diabetes" value="7"> Sibling <input type="radio" id="opt" name="diabetes" value="15"> Parent <input type="radio" id="opt" name="diabetes"
value="15">
<p> How would you describe your diet? </p>
Low sugar <input type="radio" id="opt" name="diet" value="0" checked> Normal sugar <input type="radio" id="opt" name="diet" value="0"> Quite high sugar <input type="radio" id="opt" name="diet" value="7"> High sugar <input type="radio" id="opt" name="diet"
value="10">
<button id="calculate" name="button_calculate" value="Calculate" onclick="calculateAndPrintRisk();">Calculate</button>
</div>
</div>
Note that your if else could be simplified to
function calculateAndPrintRisk(){
alert("your risk is "+(riskTotal<=15?"low":(riskTotal<=25?"medium":"high")));
}
Related
So I was tasked with creating a menu in which the user will choose between four noodles, four main dishes, and three sides. The sides will multiply the price of the main dish. The catch is that for every noodle the user checked, it will be incremented to the total price by 50%. So, if the user pays $120 and chooses two noodles, it will be $180.
I know that the checkbox will call for two functions, but I have no clue as to how it would work only if there are two or more checked checkboxes. Can someone help or guide me into how to actually perform this?
Fiddle
function pmodel() {
Model();
finalCost();
}
function Model() {
if (document.querySelector('input[name="NDLS"]:checked')) {
document.getElementById("MMD").disabled = false;
document.getElementById("ADDONS").disabled = false;
} else {
document.getElementById("MMD").disabled = true;
document.getElementById("ADDONS").disabled = true;
}
}
function total() {
var selected1 = document.querySelector('input[name="MD"]:checked').value;
var selected2 = document.querySelector('input[name="ADDONS"]:checked').value;
//var totals = 0;
totals = (selected1 * selected2);
finalCost(totals);
}
function finalCost(totals) {
//totals += (totals * document.querySelector('input[id="PMODEL"]').value);
document.getElementById("amount").value = totals;
}
<fieldset id="MNDLS">
<legend>Noodles</legend>
<input type="checkbox" name="NDLS" id="PNDLS" value="0.5" onclick="pmodel()">
<label for="Model">Spaghetti</label><br>
<input type="checkbox" name="NDLS" id="PNDLS" value="0.5" onclick="pmodel()">
<label for="Model">Carbonara</label><br>
<input type="checkbox" name="NDLS" id="PNDLS" value="0.5" onclick="pmodel()">
<label for="Model">Lasagna</label><br>
<input type="checkbox" name="NDLS" id="PNDLS" value="0.5" onclick="pmodel()">
<label for="Model">Plain</label>
</fieldset>
<fieldset id="MMD" disabled>
<legend>Main Dish</legend>
<input type="radio" name="MD" value="50" onclick="total()">
<label>Chicken Wings ($50)</label><br>
<input type="radio" name="MD" value="55" onclick="total()">
<label>Chicken Breast ($55)</label><br>
<input type="radio" name="MD" value="60" onclick="total()">
<label>Pork Cutlets ($60)</label><br>
<input type="radio" name="MD" value="65" onclick="total()">
<label>Steak($65)</label>
</fieldset>
<fieldset id="ADDONS" disabled>
<legend>Sides</legend>
<input type="radio" name="ADDONS" value="1" onclick="total()">
<label>Nothing (100%)</label><br>
<input type="radio" name="ADDONS" value="1.5" onclick="total()">
<label>Softdrinks (150%)</label><br>
<input type="radio" name="ADDONS" value="2" onclick="total()">
<label>Softdrinks and Fries (200%)</label>
</fieldset>
<br>
<p><strong>Amount (US$)</strong>: <input type="text" name="amount" id="amount" value="" /></p>
First of all don't use same ID more than once, they should be unique.
Instead of that you can set your checkboxes with same class (just for ease selecting) and then count how many of them are checked:
function pmodel() {
var count = 0;
var list=document.getElementsByClassName("PNDLS");
for (var i = 0; i < list.length; ++i) { if(list[i].checked) { count++; } }
console.log(count);
}
<fieldset id="MNDLS">
<legend>Noodles</legend>
<input type="checkbox" name="NDLS" class="PNDLS" value="0.5" onclick="pmodel()">
<label for="Model">Spaghetti</label><br>
<input type="checkbox" name="NDLS" class="PNDLS" value="0.5" onclick="pmodel()">
<label for="Model">Carbonara</label><br>
<input type="checkbox" name="NDLS" class="PNDLS" value="0.5" onclick="pmodel()">
<label for="Model">Lasagna</label><br>
<input type="checkbox" name="NDLS" class="PNDLS" value="0.5" onclick="pmodel()">
<label for="Model">Plain</label>
</fieldset>
<fieldset id="MMD" disabled>
<legend>Main Dish</legend>
<input type="radio" name="MD" value="50" onclick="total()">
<label>Chicken Wings ($50)</label><br>
<input type="radio" name="MD" value="55" onclick="total()">
<label>Chicken Breast ($55)</label><br>
<input type="radio" name="MD" value="60" onclick="total()">
<label>Pork Cutlets ($60)</label><br>
<input type="radio" name="MD" value="65" onclick="total()">
<label>Steak($65)</label>
</fieldset>
<fieldset id="ADDONS" disabled>
<legend>Sides</legend>
<input type="radio" name="ADDONS" value="1" onclick="total()">
<label>Nothing (100%)</label><br>
<input type="radio" name="ADDONS" value="1.5" onclick="total()">
<label>Softdrinks (150%)</label><br>
<input type="radio" name="ADDONS" value="2" onclick="total()">
<label>Softdrinks and Fries (200%)</label>
</fieldset>
<br>
<p><strong>Amount (US$)</strong>: <input type="text" name="amount" id="amount" value="" /></p>
how I am supposed to write some code which gets the values of all the selected checkboxes, adds them up, and then adds on the value of the selected size as well
this is my code for html. I am still dint figure yet for the java script part
<form name="order_submit" method="post" action="" onSubmit="">
<h1>My Pizza Cafe</h1>
<br>
<h3>Step 2: Select the pizza you want:</h3>
<input type="radio" name="pizza" value="15">Small
<input type="radio" name="pizza" value="20">Medium
<input type="radio" name="pizza" value="25">Large
<h3>Step 3: Select the topping you want:</h3>
<input type="checkbox" name="topping" value="5" onclick="onlyOne(this)"> Pepperoni
<input type="checkbox" name="topping" value="7" onclick="onlyOne(this)"> Sausage
<input type="checkbox" name="topping" value="5" onclick="onlyOne(this)"> Mushroom <br>
<input type="checkbox" name="topping" value="4" onclick="onlyOne(this)"> Pineapple
<input type="checkbox" name="topping" value="4" onclick="onlyOne(this)"> Black Olives
<input type="checkbox" name="topping" value="7" onclick="onlyOne(this)"> Meatball
<br><br>
<input type="submit" name="send" value="Submit Order">
<input type="reset" value="Clear Entries">
</form>
Here you go (with jQuery). Add when checked, subtract when unchecked again.
Error handling etc. is up to you
This is a mix out of different solution ideas:
Always update the current value (as done here with the toppings). This is useful when you want to display the current total
Calculate the sum when the form is submitted. Then you need to iterate through all checked checkboxes and sum up their values.
let toppingsValue = 0;
$("input[type='checkbox']").change(function() {
if (this.checked) {
toppingsValue += parseInt(this.value);
} else {
toppingsValue -= parseInt(this.value);
}
});
$("form").submit(() => {
const selectedPizza = $("input[name='pizza']:checked");
const total = toppingsValue + parseInt(selectedPizza.val());
alert("total: " + total);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="order_submit" method="post" action="">
<h1>My Pizza Cafe</h1>
<br>
<h3>Step 2: Select the pizza you want:</h3>
<input type="radio" name="pizza" value="15">Small
<input type="radio" name="pizza" value="20">Medium
<input type="radio" name="pizza" value="25">Large
<h3>Step 3: Select the topping you want:</h3>
<input type="checkbox" name="topping" value="5"> Pepperoni
<input type="checkbox" name="topping" value="7"> Sausage
<input type="checkbox" name="topping" value="5"> Mushroom <br>
<input type="checkbox" name="topping" value="4"> Pineapple
<input type="checkbox" name="topping" value="4"> Black Olives
<input type="checkbox" name="topping" value="7"> Meatball
<br><br>
<input type="submit" name="send" value="Submit Order">
<input type="reset" value="Clear Entries">
</form>
I have a form/questionnaire where the user must choose various options in HTML.
Javascript will then add up all the options; there are more forms that will be added up to create a grand total.
I know that I need to use parseInt and various if statements:
if option 1 is selected, return value
if option 2 is selected, return value
and so on..
HTML:
<input type="radio" name="age" id= "age1" value="0" checked> 1-25<br>
<input type="radio" name="age" id= "age2" value="5"> 26-40<br>
<input type="radio" name="age" id= "age3" value="8"> 41-60<br>
<input type="radio" name="age" id= "age4" value="10"> 60+<br>
Javascript:
calculateAge () {
var age = parseInt (document.getElementById('age1').value)
if (age = checked) return age;
console.log('age')
}
I assume you want to do a sum over all selected radio button values on click of e.g. a button.
The core of this apporach is to only select those radio buttons which are checked input[type=radio]:checked. If you have those, it's easy to use Array.prototype.reduce to boil that collection down to the sum.
calc.addEventListener('click', sumToVariable)
var sum;
function sumUp() {
let sum = [...document.querySelectorAll('input[type=radio]:checked')]
.reduce(
(acc, val) => acc + Number(val.value)
, 0
)
result.textContent = sum;
return sum;
}
function sumToVariable() {
sum = sumUp();
console.log(sum);
}
body {
font-size: 10px;
}
#result:not(:empty)::before {
content: "Sum of selected options: ";
}
<input type="radio" name="age" id="age1" value="0" checked> 1-25<br>
<input type="radio" name="age" id="age2" value="5"> 26-40<br>
<input type="radio" name="age" id="age3" value="8"> 41-60<br>
<input type="radio" name="age" id="age4" value="10"> 60+<br>
<hr />
<input type="radio" name="age2" id="age10" value="0" checked> 1-25<br>
<input type="radio" name="age2" id="age20" value="5"> 26-40<br>
<input type="radio" name="age2" id="age30" value="8"> 41-60<br>
<input type="radio" name="age2" id="age40" value="10"> 60+<br>
<hr />
<button type="button" id="calc">Calc</button>
<div id="result"></div>
You could as well do the same on change of a radio button:
radiobuttons.addEventListener('change', () => {
result.textContent = [...document.querySelectorAll('input[type=radio]:checked')]
.reduce(
(acc, val) => acc + Number(val.value)
, 0
)
}
)
body {
font-size: 10px;
}
#result:not(:empty)::before {
content: "Sum of selected options: ";
}
<div id="radiobuttons">
<input type="radio" name="age" id="age1" value="0" checked> 1-25<br>
<input type="radio" name="age" id="age2" value="5"> 26-40<br>
<input type="radio" name="age" id="age3" value="8"> 41-60<br>
<input type="radio" name="age" id="age4" value="10"> 60+<br>
<hr />
<input type="radio" name="age2" id="age10" value="0" checked> 1-25<br>
<input type="radio" name="age2" id="age20" value="5"> 26-40<br>
<input type="radio" name="age2" id="age30" value="8"> 41-60<br>
<input type="radio" name="age2" id="age40" value="10"> 60+<br>
</div>
<hr />
<div id="result"></div>
age = checked
cannot work, because age is an int, and a single equal sign is not used for comparison. Also checked is a property and not a comparable. You could use it like so:
function calculateAge () {
let age = parseInt (document.getElementById('age1').value)
if (document.getElementById('age1').checked) return age;
console.log('age')
}
Also you didnt ask a question, assuming you want to know why there is nothing returned.
I'm a newbie coder and cannot for the life of me figure out how to add up values for radio buttons below - any help would be greatly appreciated!
I am trying to create a diabetes screening assessment tool - where you will be able to assign different values to different risk factors.
You would need to use JavaScript to accomplish this.
Here's one way to do it:
Listen for the form's submit event
Prevent the default (so that the form doesn't get sent to the server)
Grab the value from each field. Fields use the name attribute from the HTML
Use parseInt on each field because they'll be strings
Add them up
Display the result (in this example, in the console)
const form = document.querySelector('form')
form.addEventListener('submit', event => {
event.preventDefault()
const total =
parseInt(form.age.value) +
parseInt(form.bmi.value) +
parseInt(form.famhistory.value) +
parseInt(form.diet.value)
console.log(total)
})
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Zedland Health Authority's Diabetes health assessment tool</title>
<link rel="stylesheet" type="text/css" href="fma.css">
<script src="fma.js"></script>
</head>
<body>
<h1 id="pageheading">Zedland Health Authority's Diabetes health assessment tool</h1>
<form id="register">
<fieldset id="controls">
<div>
<label class="button" for="Age">How old are you?</label>
<input type="radio" id="agerange" name="age" value="0" checked="checked">
<label for="agerange1">1-25</label>
<input type="radio" id="agerange" name="age" value="5">
<label for="agerange2">26-40</label>
<input type="radio" id="agerange" name="age" value="8">
<label for="agerange3">40-60</label>
<input type="radio" id="agerange" name="age" value="10">
<label for="agerange4">60+</label>
</div>
<div>
<label class="button" for="bmi">What is your BMI?</label>
<input type="radio" id="bmi" name="bmi" value="0" checked="checked">
<label for="bmi1">0-25</label>
<input type="radio" id="bmi" name="bmi" value="0">
<label for="bmi2">26-30</label>
<input type="radio" id="bmi" name="bmi" value="9">
<label for="bmi3">31-35</label>
<input type="radio" id="bmi" name="bmi" value="10">
<label for="bmi4">35+</label>
</div>
<div>
<label class="button" for="famhistory">Does anybody in your family have diabetes?</label>
<input type="radio" id="famhistory" name="famhistory" value="0" checked="checked">
<label for="famhistory1">No</label>
<input type="radio" id="famhistory" name="famhistory" value="7">
<label for="famhistory2">Grandparent</label>
<input type="radio" id="famhistory" name="famhistory" <label for="famhistory3">Sibling</label>
<input type="radio" id="famhistory" name="famhistory" value="15">
<label for="famhistory4">Parent</label>
</div>
<div>
<label class="button" for="diet">How would you describe your diet?</label>
<input type="radio" id="diet" name="diet" value="0" checked="checked">
<label for="diet1">Low sugar</label>
<input type="radio" id="diet" name="diet" value="7">
<label for="diet2">Normal sugar</label>
<input type="radio" id="diet" name="diet" value="15">
<label for="diet3">Quite high sugar</label>
<input type="radio" id="diet" name="diet" value="15">
<label for="diet4">High sugar</label>
</div>
</fieldset>
<div>
<input type="submit" value="submit" id="submit">
</div>
</form>
</body>
</html>
If you plan on adding values, here is a more flexible approach.
The idea is to loop through each relevant input (those that are inside your fieldset with ID controls), regardless of its name, so that if you add more checks, the same code will still work.
Create a score variable and increment it with the value of each input that is checked.
Be careful, you have the value 0 TWICE for the BMI check
window.addEventListener('DOMContentLoaded', function() {
var form = document.querySelector('form');
form.addEventListener('submit', function(event) {
event.preventDefault();
var inputs = document.querySelectorAll('#controls input');
var score = 0;
inputs.forEach(function(input) {
if (input.checked) {
score += parseInt(input.value, 10);
}
});
console.log(score);
});
});
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Zedland Health Authority's Diabetes health assessment tool</title>
<script>
</script>
</head>
<body>
<h1 id="pageheading">Zedland Health Authority's Diabetes health assessment tool</h1>
<form id="register">
<fieldset id="controls">
<div>
<label class="button" for="Age">How old are you?</label>
<input type="radio" id="agerange" name="age" value="0" checked="checked">
<label for="agerange1">1-25</label>
<input type="radio" id="agerange" name="age" value="5">
<label for="agerange2">26-40</label>
<input type="radio" id="agerange" name="age" value="8">
<label for="agerange3">40-60</label>
<input type="radio" id="agerange" name="age" value="10">
<label for="agerange4">60+</label>
</div>
<div>
<label class="button" for="bmi">What is your BMI?</label>
<input type="radio" id="bmi" name="bmi" value="0" checked="checked">
<label for="bmi1">0-25</label>
<input type="radio" id="bmi" name="bmi" value="0">
<label for="bmi2">26-30</label>
<input type="radio" id="bmi" name="bmi" value="9">
<label for="bmi3">31-35</label>
<input type="radio" id="bmi" name="bmi" value="10">
<label for="bmi4">35+</label>
</div>
<div>
<label class="button" for="famhistory">Does anybody in your family have diabetes?</label>
<input type="radio" id="famhistory" name="famhistory" value="0" checked="checked">
<label for="famhistory1">No</label>
<input type="radio" id="famhistory" name="famhistory" value="7">
<label for="famhistory2">Grandparent</label>
<input type="radio" id="famhistory" name="famhistory"
<label for="famhistory3">Sibling</label>
<input type="radio" id="famhistory" name="famhistory" value="15">
<label for="famhistory4">Parent</label>
</div>
<div>
<label class="button" for="diet">How would you describe your diet?</label>
<input type="radio" id="diet" name="diet" value="0" checked="checked">
<label for="diet1">Low sugar</label>
<input type="radio" id="diet" name="diet" value="7">
<label for="diet2">Normal sugar</label>
<input type="radio" id="diet" name="diet" value="15">
<label for="diet3">Quite high sugar</label>
<input type="radio" id="diet" name="diet" value="15">
<label for="diet4">High sugar</label>
</div>
</fieldset>
<div>
<input type="submit" value="submit">
</div>
</form>
</body>
</html>
I am working on making a form that should take the three questions in the form and add them up. If the end value is equal to three it should open call another function called toggletab() when the submit button is clicked. I tried this with it telling me pass or false depending on the value but it won't work. I am not good at JavaScript and it is really confusing to me. It looks like it is running each question separately instead of waiting until the end and calculating them all together. I cannot figure out why this is happening. I also am not sure how to call another function that is in a separate file if someone would know how to do that.
Thank you. This is the HTML
<fieldset class="article">
<legend>Have you had your record expunged before?</legend>
<input type="radio" name="field1" value="0" />
<label>
Yes
</label>
<input type="radio" name="field1" value="1" />
<label>
No
</label>
</fieldset>
<fieldset class="article">
<legend>Do you have any charges pending against you?</legend>
<input type="radio" name="field2" value="0" onclick="getscores2(this)" />
<label>
Yes
</label>
<input type="radio" name="field2" value="1" onclick="getscores2(this)" />
<label>
No
</label>
</fieldset>
<fieldset>
<legend>Is your drivers license suspended?</legend>
<input type="radio" name="field3" value="0" onclick="getscores3(this)"/>
<label>
Yes
</label>
<input type="radio" name="field3" value="1" onclick="getscores3(this)"/>
<label>
No
</label>
</fieldset>
<fieldset id="submitbutton" class="article">
<input type="button" id="submit" value="submit" onclick='answer()' />
</fieldset>
</form>
<p id="totalScore">this is answer </p>
<button onclick = "toggletab()" id="tabButton"><h3>first results</h3>
</button>
<form>
<div id="first" >
<fieldset>
<label>
<fieldset class="article">
<legend>Have you had your record expunged before?</legend>
<input type="radio" name="field1" value="0" />
<label>
Yes
</label>
<input type="radio" name="field1" value="1" />
<label>
No
</label>
</fieldset>
<fieldset class="article">
<legend>Do you have any charges pending against you?</legend>
<input type="radio" name="field2" value="0" onclick="getscores2(this)" />
<label>
Yes
</label>
<input type="radio" name="field2" value="1" onclick="getscores2(this)" />
<label>
No
</label>
</fieldset>
<fieldset>
<legend>Is your drivers license suspended?</legend>
<input type="radio" name="field3" value="0"
onclick="getscores3(this)"/>
<label>
Yes
</label>
<input type="radio" name="field3" value="1"
onclick="getscores3(this)"/>
<label>
No
</label>
</fieldset>
<fieldset id="submitbutton" class="article">
<input type="button" id="submit" value="submit" onclick='answer()' />
</fieldset>
</form>
<p id="totalScore">this is answer </p>
<button onclick = "toggletab()" id="tabButton"><h3>first results</h3>
</button>
<form>
<div id="first" >
<fieldset>
<label>
<legend>Is your arrest record a:</legend>
<input type="radio" name="field4" value="1"
onclick="getscores4(this)"/>
IC 35-38-9-1
</label>
<label>
<input type="radio" name="field4" value="2"
onclick="getscores4(this)"/>
IC 35-38-9-2
</label>
<label>
<input type="radio" name="field4" value="3"
onclick="getscores4(this)"/>
IC 35-38-9-3
</label>
<label>
<input type="radio" name="field4" value="4"
onclick="getscores4(this)"/>
IC 35-38-9-4
</label>
<label>
<input type="radio" name="field4" value="5"
onclick="getscores4(this)"/>
IC 35-38-9-5
</label>
</fieldset>
This is the JavaScript
function getscores1(score1) {
var getscores1 = (score1.value);
sendScores(getscores1);
}
function getscores2(score2) {
var getscores2 = (score2.value);
sendScores(getscores2);
}
function getscores3(score3) {
var getscores3 = (score3.value);
sendScores(getscores3);
}
function sendScores(getscores1, getscores2, getscores3){
var total = getscores1 + getscores2 + getscores3;
answer(total);
}
function answer(total) {
if (total == 3) {
document.getElementById('totalScore').innerHTML = "false";
} else{
document.getElementById('totalScore').innerHTML = "pass";
}
}
The variables your functions are defining are not global. Their values disappear after the function returns. So your sendScores function does not actually have access to those values unless you pass them as arguments. But while sendScores takes 3 arguments, you are only sending one (the one you have access too when you call the function).
One option would be to store these as global variables, but global variables are Generally Evilâ„¢. Alternatively, you can get all the values when you click submit. Here is a working example. Note this does not catch the case when the user does not respond to one or more of the questions. Click the "run snippet" button below to see it in action.
For your final question, you can put your js in a separate file and then put <script src="path/to/your/file/js"></script> in your html to load it.
function answer(total) {
var score = 0;
if (document.getElementById('exp_yes').checked) {
score++;
}
if (document.getElementById('chg_yes').checked) {
score++;
}
if (document.getElementById('sus_yes').checked) {
score++;
}
if (score > 0) {
document.getElementById('totalScore').innerHTML = "false";
} else {
document.getElementById('totalScore').innerHTML = "pass";
}
}
<fieldset class="article">
<legend>Have you had your record expunged before?</legend>
<input id=exp_yes type="radio" name="field1" value="0" />
<label>
Yes
</label>
<input id=exp_no type="radio" name="field1" value="1" />
<label>
No
</label>
</fieldset>
<fieldset class="article">
<legend>Do you have any charges pending against you?</legend>
<input id=chg_yes type="radio" name="field2" value="0" />
<label>
Yes
</label>
<input id=chg_no type="radio" name="field2" value="1" />
<label>
No
</label>
</fieldset>
<fieldset>
<legend>Is your drivers license suspended?</legend>
<input id=sus_yes type="radio" name="field3" value="0" />
<label>
Yes
</label>
<input id=sus_no type="radio" name="field3" value="1" />
<label>
No
</label>
</fieldset>
<fieldset id="submitbutton" class="article">
<input type="button" id="submit" value="submit" onclick='answer()' />
</fieldset>
</form>
<p id="totalScore">this is answer </p>