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>
Related
I'm using a multi-step form from this question and answer on StackOverflow
To add to this form;
1.) how can it work with conditional logic, as in, if the user's input radio first question is to choose ppc or organic, if they select organic then only certain "hidden" divs with "organic" class show, and the PPC related divs don't. But the other neutral hidden divs will show later. I think the problem is they are all hidden already so the first script seems to override the second javascript that looks for "if this... else".
2.)A second problem with the multi-step form without buttons above is you cannot tab to a second or third input text field on the last page. It just blanks out.
<script type='text/javascript'>
$(document).ready(function(){
$('#traffic').on('change', function() {
if ( this.value == 'organic' )
{
$(".org").show();
$(".ppc").hide();
}
else
{
$(".org").hide();
$(".ppc").show();
}
});
});
</script>
<script type="text/javascript">
document.querySelector("form").onchange = function(e) {
var currentFormPage = e.target.parentElement.parentElement;
console.log(e.target.name + ": " + e.target.value);
if(currentFormPage.nextElementSibling) {
currentFormPage.classList.add("hidden");
currentFormPage.nextElementSibling.classList.remove("hidden");
}
}
</script>
<form>
<h2>Free Google Ads Audit!</h2>
<div>
<h4>Do you want Organic or PPC traffic right now?</h4>
<label class="radio-choice" style="display: none"><input type="radio" name="traffic" id="traffic" value="" checked></label>
<label class="radio-choice"><input type="radio" name="traffic" id="traffic" value="organic">Organic is the best</label>
<label class="radio-choice"><input type="radio" name="traffic" id="traffic" value="ppc">PPC is better</label>
</div>
<div class="hidden ppc">
<h4>What's your monthly ads budget?</h4>
<label class="radio-choice" style="display: none"><input type="radio" name="whats_your_monthly_ads_budget" value="" checked></label>
<label class="radio-choice"><input type="radio" name="whats_your_monthly_ads_budget" value="2000-10000">2,000 - 10,000</label>
<label class="radio-choice"><input type="radio" name="whats_your_monthly_ads_budget" value="11000-50000">11,000 - 50,000</label>
<label class="radio-choice"><input type="radio" name="whats_your_monthly_ads_budget" value="51000-100000">51,000 - 100,000</label>
<label class="radio-choice"><input type="radio" name="whats_your_monthly_ads_budget" value="+100000">100,000+</label>
</div>
<div class="hidden ppc">
<h4>Have you ever had an Adwords account?</h4>
<label class="radio-choice" style="display: none"><input type="radio" name="adwords" value="" checked></label>
<label class="radio-choice"><input type="radio" name="food" id="adwords" value="2-3 years">Yes</label>
<label class="radio-choice"><input type="radio" name="food" id="adwords" value="5 years">No</label>
</div>
<div class="hidden org">
<h4>How much experience do you have?</h4>
<label class="radio-choice" style="display: none"><input type="radio" name="experience" value="" checked></label>
<label class="radio-choice"><input type="radio" name="exp" id="experience" value="2-3 years">2-3 years</label>
<label class="radio-choice"><input type="radio" name="exp" id="experience" value="5 years">5 years</label>
</div>
<div class="hidden">
<h4>What are your Goal(s)?</h4>
<label class="radio-choice" style="display: none"><input type="radio" name="what_are_your_goals" value="" checked></label>
<label class="radio-choice"><input type="radio" name="what_are_your_goals" value="Lead Generation">Lead Generation</label>
<label class="radio-choice"><input type="radio" name="what_are_your_goals" value="Brand Awareness">Brand Awareness</label>
<label class="radio-choice"><input type="radio" name="what_are_your_goals" value="Online Sales">Online Sales</label>
<label class="radio-choice"><input type="radio" name="what_are_your_goals" value="Sign-ups">Sign-ups</label>
</div>
<div class="hidden">
<h4>Success! You qualify for a Free Google Ads Audit, enter your email to confirm!</h4>
<input type="text" placeholder="Full name">
<input type="email" placeholder="Company Email">
<input type="button" name="email" value="Download">
</div>
</form>
This should work how you want it. Unfortunately, jquery invokes the first id as they're unique so if you want multiple elements to do the same functionality you'll have to make them all classes.
<html>
<head>
<title>Test</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<style>
.hidden {
display: none;
}
</style>
<script>
$(document).ready(function() {
$('.traffic').on('change', function() {
if (this.value === "organic") {
$(".org").show();
$(".ppc").hide();
} else {
$(".org").hide();
$(".ppc").show();
}
});
});
</script>
</head>
<body>
<form>
<h2>Free Google Ads Audit!</h2>
<div>
<h4>Do you want Organic or PPC traffic right now?</h4>
<label class="radio-choice" style="display: none">
<input type="radio" name="traffic" id="traffic" value="" checked>
</label>
<label class="radio-choice">
<input type="radio" name="traffic" class="traffic" value="organic">Organic is the best </label>
<label class="radio-choice">
<input type="radio" name="traffic" class="traffic" value="ppc">PPC is better </label>
</div>
<div class="hidden ppc">
<h4>What's your monthly ads budget?</h4>
<label class="radio-choice" style="display: none">
<input type="radio" name="whats_your_monthly_ads_budget" value="" checked>
</label>
<label class="radio-choice">
<input type="radio" name="whats_your_monthly_ads_budget" value="2000-10000">2,000 - 10,000 </label>
<label class="radio-choice">
<input type="radio" name="whats_your_monthly_ads_budget" value="11000-50000">11,000 - 50,000 </label>
<label class="radio-choice">
<input type="radio" name="whats_your_monthly_ads_budget" value="51000-100000">51,000 - 100,000 </label>
<label class="radio-choice">
<input type="radio" name="whats_your_monthly_ads_budget" value="+100000">100,000+ </label>
</div>
<div class="hidden ppc">
<h4>Have you ever had an Adwords account?</h4>
<label class="radio-choice" style="display: none">
<input type="radio" name="adwords" value="" checked>
</label>
<label class="radio-choice">
<input type="radio" name="food" id="adwords" value="2-3 years">Yes </label>
<label class="radio-choice">
<input type="radio" name="food" id="adwords" value="5 years">No </label>
</div>
<div class="hidden org">
<h4>How much experience do you have?</h4>
<label class="radio-choice" style="display: none">
<input type="radio" name="experience" value="" checked>
</label>
<label class="radio-choice">
<input type="radio" name="exp" id="experience" value="2-3 years">2-3 years </label>
<label class="radio-choice">
<input type="radio" name="exp" id="experience" value="5 years">5 years </label>
</div>
<div class="hidden">
<h4>What are your Goal(s)?</h4>
<label class="radio-choice" style="display: none">
<input type="radio" name="what_are_your_goals" value="" checked>
</label>
<label class="radio-choice">
<input type="radio" name="what_are_your_goals" value="Lead Generation">Lead Generation </label>
<label class="radio-choice">
<input type="radio" name="what_are_your_goals" value="Brand Awareness">Brand Awareness </label>
<label class="radio-choice">
<input type="radio" name="what_are_your_goals" value="Online Sales">Online Sales </label>
<label class="radio-choice">
<input type="radio" name="what_are_your_goals" value="Sign-ups">Sign-ups </label>
</div>
<div class="hidden">
<h4>Success! You qualify for a Free Google Ads Audit, enter your email to confirm!</h4>
<input type="text" placeholder="Full name">
<input type="email" placeholder="Company Email">
<input type="button" name="email" value="Download">
</div>
</form>
</body>
</html>
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>
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>
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")));
}
<!doctype html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width , initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="css/Quiz.css">
<script>
var xmlh,url;
xmlh = new XMLHttpRequest();
url="AnswerFile.txt";
xmlh.onreadystatechange=function(){
if(xmlh.readyState == 4 && xmlh.status ==200){
var myArr =JSON.parse(xmlh.responseText);
myFunctuion(myArr);
}
};
xmlh.open("GET",url,true);
xmlh.send();
function myFunctuion(arr){
var dom=document.getElementById("demo");
var cha=document.getElementById("radio1");
var chb=document.getElementById("radio2");
var chc=document.getElementById("radio3");
dom.innerHTML = "<h3>" +arr[0].question+ "</h3>";
cha.innerHTML = arr[0].ChA ;
chb.innerHTML = arr[0].ChB ;
chc.innerHTML = arr[0].ChC ;
}
</script>
<head>
<html>
<body>
<div class="w3-content" >
<form class="w3-container w3-card-4 w3-label">
<label id="demo"></label>
<input class="w3-radio" type="radio" name="ChA" value="a"> <label id="radio1"></label></input></br>
<input class="w3-radio" type="radio" name="ChB" value="b"><label id="radio2"></label> </input></br>
<input class="w3-radio" type="radio" name="ChC" value="c"> <label id="radio3"></label></input></br>
<br>
<br>
<input class="w3-btn w3-xlarge w3-dark-grey w3-hover-light-grey w3-center w3-section w3-border w3-round-xlarge " style="font-weight:900;" type="submit" value="Submit Answers">
</form>
</div>
</body>
</html>
i get my all question and option from text file by JSON and i succeeded it .
But my main problem is all my radio button is checked where i want to if one button is checked then other button is unchecked .
what my problem in code ? what i do? and why cause this problem ?
?** for style i use W3.CSS **?
Your HTML input radio should have the same name attribute, like this:
<input class="w3-radio" type="radio" name="Ch" value="a"> <label id="radio1"></label></input></br>
<input class="w3-radio" type="radio" name="Ch" value="b"><label id="radio2"></label> </input></br>
<input class="w3-radio" type="radio" name="Ch" value="c"> <label id="radio3"></label></input></br>
Your radio buttons should all use the same name :)
<input class="w3-radio" type="radio" name="Ch" value="a"> <label id="radio1"></label></input></br>
<input class="w3-radio" type="radio" name="Ch" value="b"><label id="radio2"></label> </input></br>
<input class="w3-radio" type="radio" name="Ch" value="c"> <label id="radio3"></label></input></br>
Name of your radio input fields should be same for specific question's options. Like below:
First group of radios
<input type="radio" name="rad" value="radopt1" id="radopt1"><label for="radopt1">Radio Option1</label></input>
<input type="radio" name="rad" value="radopt2" id="radopt2"><label for="radopt2">Radio Option2</label> </input>
<input type="radio" name="rad" value="radopt3" id="radopt3"><label for="radopt3">Radio Option3</label></input>
Second group of radios
<input type="radio" name="rad1" value="rad1opt1" id="rad1opt1"><label for="rad1opt1">Radio1 Option1</label></input>
<input type="radio" name="rad1" value="rad1opt2" id="rad1opt2"><label for="rad1opt2">Radio1 Option2</label> </input>
<input type="radio" name="rad1" value="rad1opt3" id="rad1opt3"><label for="rad1opt3">Radio1 Option3</label></input>