Can't get radio values to send - javascript

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>

Related

How do I check if another checkbox is checked and perform the function again with added conditions?

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>

jQuery multi-step form: disable next button when fields unchecked

I have a multi-step form that has a "next" and "back" button on each step of the form. I'm using jQuery to enable the "next" button once the criteria for each section is met. For example: at least one checkbox is checked or a radio button is selected.
I'm having an issue where after completing a number of sections, I go back to a previous section and uncheck all checkboxes and the "next" button remains enabled.
There's a Codepen here of a rough version of what I'm working with - note all sections are visible to show how the button remains enabled once you begin checking/unchecking: https://codepen.io/abbasarezoo/pen/jZgQOV
My current code:
<form>
<fieldset class="panels">
<h2>1: Select multiple answers</h2>
<label for="checkbox-1">Checkbox 1</label>
<input type="checkbox" id="checkbox-1" name="checkbox" />
<label for="checkbox-2">Checkbox 2</label>
<input type="checkbox" id="checkbox-2" name="checkbox" />
<label for="checkbox-3">Checkbox 3</label>
<input type="checkbox" id="checkbox-3" name="checkbox" />
<br />
<button type="button" class="next-q" disabled>Next</button>
</fieldset>
<fieldset class="panels">
<h2>2: Select multiple answers</h2>
<label for="checkbox-4">Checkbox 1</label>
<input type="checkbox" id="checkbox-4" name="checkbox" />
<label for="checkbox-5">Checkbox 2</label>
<input type="checkbox" id="checkbox-5" name="checkbox" />
<label for="checkbox-6">Checkbox 3</label>
<input type="checkbox" id="checkbox-6" name="checkbox" />
<br />
<button type="button" class="next-q" disabled>Next</button>
</fieldset>
<fieldset class="panels">
<h2>3: Select one answer</h2>
<label for="radio-1">Radio 1</label>
<input type="radio" id="radio-1" name="radio" />
<label for="radio-2">Radio 2</label>
<input type="radio" id="radio-2" name="radio" />
<label for="radio-2">Radio 3</label>
<input type="radio" id="radio-3" name="radio" />
<br />
<button type="button" class="next-q" disabled>Next</button>
<button type="button" class="previous-q">Previous</button>
</fieldset>
<fieldset class="rows">
<h2>4: Select one answer per row</h2>
<div class="radio-row">
<h3>Row 1</h3>
<label for="radio-4">Radio 1</label>
<input type="radio" id="radio-4" name="radio-row-1" />
<label for="radio-5">Radio 2</label>
<input type="radio" id="radio-5" name="radio-row-1" />
<label for="radio-6">Radio 3</label>
<input type="radio" id="radio-6" name="radio-row-1" />
</div>
<div class="radio-row">
<h3>Row 2</h3>
<label for="radio-7">Radio 1</label>
<input type="radio" id="radio-7" name="radio-row-2" />
<label for="radio-8">Radio 2</label>
<input type="radio" id="radio-8" name="radio-row-2" />
<label for="radio-9">Radio 3</label>
<input type="radio" id="radio-9" name="radio-row-2" />
</div>
<button type="button" class="next-q" disabled>Next</button>
<button type="button" class="previous-q">Previous</button>
</fieldset>
</form>
JS:
var $panelsInput = $('.panels input'),
$rowsInput = $('.rows input');
$panelsInput.click(function () {
if ($('.panels input:checked').length >= 1) {
$(this).closest('.panels').find('.next-q').prop('disabled', false);
}
else {
$(this).closest('.panels').find('.next-q').prop('disabled', true);
}
});
$rowsInput.click(function () {
var radioLength = $('.radio-row').length;
if ($('.rows input:checked').length == radioLength) {
$('.rows .next-q').prop('disabled', false);
}
else {
$('.rows .next-q').prop('disabled', true);
}
});
Is there any way to make this work?
when you select the input to see if is checked, you're selecting all inputs
if ($('.panels input:checked').length >= 1) {
you need to select just the inputs from the panel the user clicked
if ($(this).closest('.panels').find('input:checked').length >= 1) {
https://codepen.io/spacedog4/pen/YaWqdo?editors=1010
Please see below comment in $panelsInput.click(function (){});, you need to get the checked count for current panel (the user clicks), instead of all.
So the comparasion in your codes:
$('.panels input:checked').length >= 1
need to change to:
$(this).parent().find('input:checked').length >= 1
var $panelsInput = $('.panels input'),
$rowsInput = $('.rows input');
$panelsInput.click(function () {
//get current input, find out its parent, then get the count of checked
if ($(this).parent().find('input:checked').length >= 1) {
$(this).closest('.panels').find('.next-q').prop('disabled', false);
}
else {
$(this).closest('.panels').find('.next-q').prop('disabled', true);
}
});
$rowsInput.click(function () {
var radioLength = $('.radio-row').length;
if ($('.rows input:checked').length == radioLength) {
$('.rows .next-q').prop('disabled', false);
}
else {
$('.rows .next-q').prop('disabled', true);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<fieldset class="panels">
<h2>1: Select multiple answers</h2>
<label for="checkbox-1">Checkbox 1</label>
<input type="checkbox" id="checkbox-1" name="checkbox" />
<label for="checkbox-2">Checkbox 2</label>
<input type="checkbox" id="checkbox-2" name="checkbox" />
<label for="checkbox-3">Checkbox 3</label>
<input type="checkbox" id="checkbox-3" name="checkbox" />
<br />
<button type="button" class="next-q" disabled>Next</button>
</fieldset>
<fieldset class="panels">
<h2>2: Select multiple answers</h2>
<label for="checkbox-4">Checkbox 1</label>
<input type="checkbox" id="checkbox-4" name="checkbox" />
<label for="checkbox-5">Checkbox 2</label>
<input type="checkbox" id="checkbox-5" name="checkbox" />
<label for="checkbox-6">Checkbox 3</label>
<input type="checkbox" id="checkbox-6" name="checkbox" />
<br />
<button type="button" class="next-q" disabled>Next</button>
</fieldset>
<fieldset class="panels">
<h2>3: Select one answer</h2>
<label for="radio-1">Radio 1</label>
<input type="radio" id="radio-1" name="radio" />
<label for="radio-2">Radio 2</label>
<input type="radio" id="radio-2" name="radio" />
<label for="radio-2">Radio 3</label>
<input type="radio" id="radio-3" name="radio" />
<br />
<button type="button" class="next-q" disabled>Next</button>
<button type="button" class="previous-q">Previous</button>
</fieldset>
<fieldset class="rows">
<h2>4: Select one answer per row</h2>
<div class="radio-row">
<h3>Row 1</h3>
<label for="radio-4">Radio 1</label>
<input type="radio" id="radio-4" name="radio-row-1" />
<label for="radio-5">Radio 2</label>
<input type="radio" id="radio-5" name="radio-row-1" />
<label for="radio-6">Radio 3</label>
<input type="radio" id="radio-6" name="radio-row-1" />
</div>
<div class="radio-row">
<h3>Row 2</h3>
<label for="radio-7">Radio 1</label>
<input type="radio" id="radio-7" name="radio-row-2" />
<label for="radio-8">Radio 2</label>
<input type="radio" id="radio-8" name="radio-row-2" />
<label for="radio-9">Radio 3</label>
<input type="radio" id="radio-9" name="radio-row-2" />
</div>
<button type="button" class="next-q" disabled>Next</button>
<button type="button" class="previous-q">Previous</button>
</fieldset>
</form>
I thought it is interesting to handle interactions using event delegation at the form level which is more flexible:
Only one handler is loaded in memory. (By the way only a single scope is in charge of the logic behind the prev/next behavior).
You can add dynamically panels to the form (with the same markup structure) and buttons will work right away without requiring another listener registering step.
var $panelsInput = $('.panels input')
, $rowsInput = $('.rows input')
;
$('form').on('click', function (e) {
let $t = $(this)
, $target = $(e.target)
, $fieldset = $target.closest('fieldset')
, $rows = $fieldset.find('.radio-row')
;
// When a button is clicked
if ($target.is('button')) {
// Next button
if ($target.is('.next-q')) {
$fieldset.addClass('hide').next().addClass('show');
// Prev button
} else {
// Untick boxes
$fieldset.find('input').prop('checked', false).end()
// Disable appropriate button
.find('.next-q').prop('disabled', true).end()
.prev().removeClass('hide').nextAll().removeClass('show');
}
// When a checkbox is clicked
} else if ($target.is('input')) {
let $containers = ($rows.length ? $rows : $fieldset)
, containersHavingAtickedBox = $containers.filter(function() {
return !!$(this).find('input:checked').length
})
, shouldEnable = $containers.length === containersHavingAtickedBox.length
;
$fieldset.find('.next-q').prop('disabled', !shouldEnable);
}
});
fieldset ~ fieldset, .hide{display:none}
fieldset.show:not(.hide){display: block}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<fieldset class="panels">
<h2>1: Select multiple answers</h2>
<label for="checkbox-1">Checkbox 1</label>
<input type="checkbox" id="checkbox-1" name="checkbox" />
<label for="checkbox-2">Checkbox 2</label>
<input type="checkbox" id="checkbox-2" name="checkbox" />
<label for="checkbox-3">Checkbox 3</label>
<input type="checkbox" id="checkbox-3" name="checkbox" />
<br />
<button type="button" class="next-q" disabled>Next</button>
</fieldset>
<fieldset class="panels">
<h2>2: Select multiple answers</h2>
<label for="checkbox-4">Checkbox 1</label>
<input type="checkbox" id="checkbox-4" name="checkbox" />
<label for="checkbox-5">Checkbox 2</label>
<input type="checkbox" id="checkbox-5" name="checkbox" />
<label for="checkbox-6">Checkbox 3</label>
<input type="checkbox" id="checkbox-6" name="checkbox" />
<br />
<button type="button" class="next-q" disabled>Next</button>
</fieldset>
<fieldset class="panels">
<h2>3: Select one answer</h2>
<label for="radio-1">Radio 1</label>
<input type="radio" id="radio-1" name="radio" />
<label for="radio-2">Radio 2</label>
<input type="radio" id="radio-2" name="radio" />
<label for="radio-2">Radio 3</label>
<input type="radio" id="radio-3" name="radio" />
<br />
<button type="button" class="next-q" disabled>Next</button>
<button type="button" class="previous-q">Previous</button>
</fieldset>
<fieldset class="rows">
<h2>4: Select one answer per row</h2>
<div class="radio-row">
<h3>Row 1</h3>
<label for="radio-4">Radio 1</label>
<input type="radio" id="radio-4" name="radio-row-1" />
<label for="radio-5">Radio 2</label>
<input type="radio" id="radio-5" name="radio-row-1" />
<label for="radio-6">Radio 3</label>
<input type="radio" id="radio-6" name="radio-row-1" />
</div>
<div class="radio-row">
<h3>Row 2</h3>
<label for="radio-7">Radio 1</label>
<input type="radio" id="radio-7" name="radio-row-2" />
<label for="radio-8">Radio 2</label>
<input type="radio" id="radio-8" name="radio-row-2" />
<label for="radio-9">Radio 3</label>
<input type="radio" id="radio-9" name="radio-row-2" />
</div>
<button type="button" class="next-q" disabled>Next</button>
<button type="button" class="previous-q">Previous</button>
</fieldset>
</form>

How to add up values of radio buttons in Javascript

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>

Printing a message depending on a specific value

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

Getting radio button values for multiple radio button sets

I'm setting up a multiple choice questionnaire with the responses being handling by radio buttons labelled A, B, C and D.
I want to identify the answer to each question by getting the form ID and the clicked button value, so that, for example, a response using the first set of radio buttons might be 1B and the second, 2D and so on (the form ID script is already up and running).
I need this to work on a page with multiple sets of radio buttons
Here is the HTML:
<form class="toeic_pages" id="1">
<label class="item1">
<input type="radio" value="A" name="toeic"/>
<div class="radio-image"></div>
</label>
<label class="item2">
<input type="radio" value="B" name="toeic"/>
<div class="radio-image"></div>
</label>
<label class="item3">
<input type="radio" value="C" name="toeic"/>
<div class="radio-image"></div>
</label>
<label class="item4">
<input type="radio" value="D" name="toeic"/>
<div class="radio-image"></div>
</label>
</form>
...
<form class="toeic_pages" id="2">
<label class="item1">
<input type="radio" value="A" name="toeic"/>
<div class="radio-image"></div>
</label>
<label class="item2">
<input type="radio" value="B" name="toeic"/>
<div class="radio-image"></div>
</label>
<label class="item3">
<input type="radio" value="C" name="toeic"/>
<div class="radio-image"></div>
</label>
<label class="item4">
<input type="radio" value="D" name="toeic"/>
<div class="radio-image"></div>
</label>
</form>
However, while I've been able to get a checked radio button value using this:
jQuery('input[name=toeic]').change(function(){
var invar = jQuery('input[name=toeic]:checked').val();
alert(invar);
});
The script is only effective within the first row of buttons clicked.
To illustrate, if in the first row of buttons to be accessed, button B is clicked then B is displayed (correct).
But, if in another row, button C clicked, B is displayed (incorrect) .. and B continues to be displayed for all subsequent button clicks. I've checked out the SO pages on this but I haven't been able to find a solution - the issue seems to be multiple sets of radio buttons.
Any help would be very much appreciated
You could do something like this :
$(document).ready(function() {
$("#finish").click(function() {
var answersList = [];
//Loop over all questoins
$(".toeic_pages").each(function() {
var questionId = $(this).attr("id");
var answer = $("input[name='toeic']:checked", $(this)).val();
//if Answer isnt provided do not update the answersList
if (answer !== undefined) {
answersList.push({
question: questionId,
answer: answer
});
}
});
console.log(answersList);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="toeic_pages" id="1">
<label class="item1">
<input type="radio" value="A" name="toeic" />
<div class="radio-image"></div>
</label>
<label class="item2">
<input type="radio" value="B" name="toeic" />
<div class="radio-image"></div>
</label>
<label class="item3">
<input type="radio" value="C" name="toeic" />
<div class="radio-image"></div>
</label>
<label class="item4">
<input type="radio" value="D" name="toeic" />
<div class="radio-image"></div>
</label>
</form>
...
<form class="toeic_pages" id="2">
<label class="item1">
<input type="radio" value="A" name="toeic" />
<div class="radio-image"></div>
</label>
<label class="item2">
<input type="radio" value="B" name="toeic" />
<div class="radio-image"></div>
</label>
<label class="item3">
<input type="radio" value="C" name="toeic" />
<div class="radio-image"></div>
</label>
<label class="item4">
<input type="radio" value="D" name="toeic" />
<div class="radio-image"></div>
</label>
</form>
<button id="finish">Get Answers</button>
I think this is exactly what you need.
$('#1 input').on('change', function() {
alert($('#1').attr('id')+$('input[name=radioName]:checked', '#1').val());
});
$('#2 input').on('change', function() {
alert($('#2').attr('id')+$('input[name=radioName]:checked', '#2').val());
});
$('#3 input').on('change', function() {
alert($('#3').attr('id')+$('input[name=radioName]:checked', '#3').val());
});
$('#4 input').on('change', function() {
alert($('#4').attr('id')+$('input[name=radioName]:checked', '#4').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="1">
Question 1
<br>
<input type="radio" name="radioName" value="A" /> A <br />
<input type="radio" name="radioName" value="B" /> B <br />
<input type="radio" name="radioName" value="C" /> C <br />
</form>
<form id="2">
Question 2
<br>
<input type="radio" name="radioName" value="A" /> A <br />
<input type="radio" name="radioName" value="B" /> B <br />
<input type="radio" name="radioName" value="C" /> C <br />
</form>
<form id="3">
Question 3
<br>
<input type="radio" name="radioName" value="A" /> A <br />
<input type="radio" name="radioName" value="B" /> B <br />
<input type="radio" name="radioName" value="C" /> C <br />
</form>
<form id="4">
Question 4
<br>
<input type="radio" name="radioName" value="A" /> A <br />
<input type="radio" name="radioName" value="B" /> B <br />
<input type="radio" name="radioName" value="C" /> C <br />
</form>
Credits to the owner of this answer #Peter J in this question How can I know which radio button is selected via jQuery?

Categories