I have a form with 5 questions and 3 different answers for each question.
e.g.
q1. whats is your favorite color?
radio button-1. value blue
radio button-2. value red
radio button-3. value grey
most of these questions have the same value (blue, red, grey), which is what I want, however, I'm trying to add all the values together at the end of the form so I can determine if the person filling out the form equals one of the values (blue, red, or grey).
I'm building this form with angularjs and this is what i have so far.
<label>Q1. what is your favorite color?</label>
<div class="form-group">
<div class="radio">
<label>
<input type="radio" ng-model="formData.color" value="blue">
blue
</label>
</div>
<div class="radio">
<label>
<input type="radio" ng-model="formData.color" value="red">
red
</label>
</div>
<div class="radio">
<label>
<input type="radio" ng-model="formData.color" value="grey">
grey
</label>
</div>
this bit of code only works if I have the values already entered into the variable
$scope.formData = { };
$scope.formData = [];
$scope.formData.sort();
var current = null;
var cnt = 0;
for (var i = 0; i < $scope.formData.length; i++) {
if ($scope.formData[i] != current) {
if (cnt > 0) {
console.log(current + ' shows ' + cnt + ' times');
}
current = $scope.formData[i];
cnt = 1;
} else {
cnt++;
}
}
if (cnt > 0) {
console.log(current + ' shows ' + cnt + ' times');
}
Here is an example solution plunker. Would it work?
controller
$scope.questions = [
'Q1. what is your favorite color?',
'Q2. what color is your car?',
'Q3. what color best represents you?'
];
$scope.formData = [];
$scope.stats = function() {
$scope.results = {};
for (var i = 0; i < $scope.formData.length; i++) {
var color = $scope.formData[i];
if(color) {
if ($scope.results.hasOwnProperty(color)) {
$scope.results[color]++;
} else {
$scope.results[color] = 1;
}
}
}
};
template
<div class="form-group" ng-repeat="q in questions">
<label>{{q}}</label>
<div class="radio">
<label>
<input type="radio" ng-model="formData[$index]" value="blue">blue
</label>
</div>
<div class="radio">
<label>
<input type="radio" ng-model="formData[$index]" value="red">red
</label>
</div>
<div class="radio">
<label>
<input type="radio" ng-model="formData[$index]" value="grey">grey
</label>
</div>
</div>
<button ng-click="stats()">show results</button>
<ul>
<li ng-repeat="(c, n) in results"> {{c}} shows {{n}} times</li>
</ul>
Related
So I got a project here with a couple of radiobuttons. The plan is to be able to select a base, a lining, color and a shading technique. The blue box to the right serves the purpose of giving the customer a live overview of example outcome of the selected parts. I want to place an image there, with a variable URL.
My plan would be to do something like: "https://www.example.com/images/calculator/base+line+color+shading.png"
Where base is gotten from the base radio input, and could be for example "fullbody"Where line is gotten from the line radio input, and could be for example "clean"Where color is gotten from the color radio input, and could be for example "colored"Where shading is gotten from the shading radio input, and could be for example "ccel"This would leave us with a variable url of "https://www.example.com/images/calculator/fullbody+clean+colored+ccel.png"
At the same time, I don't want them to have to select all of the inputs to get an overview, if they only select "fullbody", the variable URL should become "https://www.example.com/images/calculator/fullbody.png"
The artist I'm doing this for is rapidly increasing the product base and style choices, and I will be updating it over time, so a solution that is expandable with more options over time would be amazing.
As always, thank you for taking your time to read over, any answers or tips/tricks/hints or pointing in directions is greatly appreciated! Enjoy the weekend folks! <3
small overview of my project layout
data-position="1" is for base group
data-position="2" is for line group
data-position="3" is for color group
data-position="4" is for shade group
..
..
data-position="k" will be for kth value group and so on...
See working example here https://jsfiddle.net/y2khfjwp/40/
<div style="width: 50%; float: Left;">
<h2>
Base
</h2>
<input type="radio" name="base" class="main-inputs" data-position="1" value="fullbody" onchange="makeImage(this)"/>Full Body<br>
<input type="radio" name="base" class="main-inputs" data-position="1" value="halfbody" onchange="makeImage(this)"/>Half Body<br>
<input type="radio" name="base" class="main-inputs" data-position="1" value="xyzbody" onchange="makeImage(this)"/>xyz Body<br>
<input type="radio" name="base" class="main-inputs" data-position="1" value="abcbody" onchange="makeImage(this)"/>abc body<br>
<hr>
<h2>
Line
</h2>
<input type="radio" name="line" class="main-inputs" data-position="2" value="clean" onchange="makeImage(this)"/>Clean<br>
<input type="radio" name="line" class="main-inputs" data-position="2" value="clean2" onchange="makeImage(this)"/>Clean2<br>
<input type="radio" name="line" class="main-inputs" data-position="2" value="clean3" onchange="makeImage(this)"/>Clean3<br>
<input type="radio" name="line" class="main-inputs" data-position="2" value="clean4" onchange="makeImage(this)"/>Clean4<br>
<hr>
<h2>
Color
</h2>
<input type="radio" name="color" class="main-inputs" data-position="3" value="colored" onchange="makeImage(this)"/>Colored<br>
<input type="radio" name="color" class="main-inputs" data-position="3" value="colored2" onchange="makeImage(this)"/>Colored2<br>
<input type="radio" name="color" class="main-inputs" data-position="3" value="colored3" onchange="makeImage(this)"/>Colored3<br>
<input type="radio" name="color" class="main-inputs" data-position="3" value="colored4" onchange="makeImage(this)"/>Colored4<br>
<hr>
<h2>
Shade
</h2>
<input type="radio" name="shade" class="main-inputs" data-position="4" value="ccel" onchange="makeImage(this)"/>Ccel<br>
<input type="radio" name="shade" class="main-inputs" data-position="4" value="ccel2" onchange="makeImage(this)"/>Ccel2<br>
<input type="radio" name="shade" class="main-inputs" data-position="4" value="ccel3" onchange="makeImage(this)"/>Ccel3<br>
<input type="radio" name="shade" class="main-inputs" data-position="4" value="ccel4" onchange="makeImage(this)"/>Ccel4<br>
</div>
<div style="width: 50%; float: Right;">
OutPut: <img id="final-output-src" src="Please select Options" /><br><span id="final-output">Please select Options</span>
</div>
<script>
var path = [];
function makeImage(element)
{
var imagePath = "";
path[element.getAttribute('data-position')] = element.value;
imagePath = finalImagePath();
document.getElementById("final-output-src").src = imagePath;
document.getElementById("final-output").innerHTML = imagePath;
};
function finalImagePath() {
var imageSrc = "https://www.example.com/images/calculator/";
var selections = "";
for(var i=1 ; i<=path.length ; i++) {
if(typeof path[i] != 'undefined' && path[i] != '') {
if(selections == "") {
selections = selections + path[i];
} else {
selections = selections + "+" + path[i];
}
}
}
if(selections != "") {
selections = selections + ".png";
imageSrc = imageSrc + selections;
}
return imageSrc;
}
</script>
Okay here is a solution to generate the image url:
const partials = document.querySelectorAll('#partials input');
const fullBody = document.getElementById('fullbody');
const baseUrl = 'some-root-url.com/';
const fileType = '.png';
let imageUrl = baseUrl + 'some-default-url' + fileType;
// Add Event Listeners
fullBody.addEventListener('change', function(){
let checked = document.querySelectorAll('#partials input:checked');
// deselect each partial
for(let i = 0; i < checked.length; i++){
checked[i].checked = false;
}
// Set the imageUrl var to the fullbody
imageUrl = baseUrl + this.value + fileType;
// see the imageUrl!
console.log(imageUrl);
});
for(let i = 0; i < partials.length; i++){
partials[i].addEventListener('change', function(){
// uncheck fullBody if checked
fullBody.checked = false;
// init the imageUrl
imageUrl = baseUrl;
// loop through each checked option and add the value to the imageUrl
let checked = document.querySelectorAll('#partials input:checked');
for(let i = 0; i < checked.length; i++){
imageUrl += checked[i].value;
}
// add the file type
imageUrl += fileType;
// see the imageUrl!
console.log(imageUrl)
});
}
And here's the corresponding HTML
<div id="partials">
<label for="base">Base</label><input name="base" type="checkbox" value="base" /><br />
<label for="line">Line</label><input name="line" type="checkbox" value="line" /><br />
<label for="color">Color</label><input name="color" type="checkbox" value="color" /><br />
<label for="Shading">Shading</label><input name="shading" type="checkbox" value="shading" />
</div>
<label for="fullbody">Full Body</label><input name="fullbody" id="fullbody" type="checkbox" value="fullbody" />
And a JSFiddle to demo
One tip for you as well, you want to use checkboxes not radio, as radio are designed for single choices not multiselect.
Hope that helps!
/**
* #Summary: checkAllConnectedUser function, to create album
* #param: index, productObj
* #return: callback(response)
* #Description:
*/
$scope.shardBuyerKeyIdArray = [];
$scope.countBuyer = 0;
$scope.checkAllSharedBuyer = function(isChecked) {
if (isChecked) {
if ($scope.selectAll) {
$scope.selectAll = false;
} else {
$scope.selectAll = true;
}
angular.forEach($scope.selectedSharedBuyerObjectList, function(selectedBuyer) {
selectedBuyer.select = $scope.selectAll;
//IF ID WILL BE EXIST IN THE ARRAY NOT PSUH THE KEYID
if ($scope.shardBuyerKeyIdArray.indexOf(selectedBuyer.userTypeDto.keyId) == -1) {
$scope.shardBuyerKeyIdArray.push(selectedBuyer.userTypeDto.keyId);
$scope.countBuyer++;
}
});
} else {
$scope.selectAll = false;
//USED FOR UNCHECK ALL THE DATA ONE- BY-ONE
angular.forEach($scope.selectedSharedBuyerObjectList, function(selectedBuyer) {
selectedBuyer.select = $scope.selectAll;
var index = $scope.shardBuyerKeyIdArray.indexOf(selectedBuyer.userTypeDto.keyId);
$scope.shardBuyerKeyIdArray.splice(index, 1);
$scope.countBuyer--;
});
}
}
<div class="checkbox w3-margin" ng-if="selectedSharedBuyerObjectList.length > 0">
<span class="w3-right" ng-if="countBuyer">
<h5>You are selecting {{countBuyer}} buyers!</h5>
</span>
<label>
<input type="checkbox" ng-model="selectAll" ng-click="checkAllSharedBuyer(selectAll)"/>Check All
</label>
</div>
<div id="sharedRow" class="checkbox" ng-repeat="selectedBuyer in cmnBuyer = (selectedSharedBuyerObjectList | filter : userSearchInProduct
| filter : filterUser)">
<label>
<input type="checkbox" ng-model="selectedBuyer.select"
ng-change="selectedSharedBuyer($index, selectedBuyer.select, selectedBuyer.userTypeDto.keyId)"/>
{{selectedBuyer.personName}}
</label>
</div>
I have two list in which i have to count the select all checkbox length as well as single checkbox count my problem if the user un-check the ALL checkbox Checkbox count will be return -- what's the problem in my code?
$(function(){
var count = 0;
$('#sharedRow ').find('input[type=checkbox]').on('change',function(){
$('#msg').text('You are selecting '+$('#sharedRow ').find('input[type=checkbox]:checked').length+' buyers!')
})
$('#chkAll').on('change', function () {
if ($(this).is(':checked')) {
$('#sharedRow ').find('input[type=checkbox]').prop('checked', true);
$('#msg').text('You are selecting '+$('#sharedRow ').find('input[type=checkbox]:checked').length+' buyers!')
}
else {
$('#sharedRow ').find('input[type=checkbox]').prop('checked', false);
$('#msg').text('You are selecting '+$('#sharedRow ').find('input[type=checkbox]:checked').length+' buyers!')
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="checkbox w3-margin">
<span class="w3-right">
<h5 id="msg" >You are selecting 0 buyers!</h5>
</span>
<label>
<input id="chkAll" type="checkbox" />Check All
</label>
</div>
<div id="sharedRow" class="checkbox">
<label>
<input type="checkbox" value="1 Buyers" />1 Buyers
</label>
<label>
<input type="checkbox" value="2 Buyers" />2 Buyers
</label>
<label>
<input type="checkbox" value="3 Buyers" />3 Buyers
</label>
<label>
<input type="checkbox" value="4 Buyers" />4 Buyers
</label>
<label>
<input type="checkbox" value="5 Buyers" />5 Buyers
</label>
<label>
<input type="checkbox" value="6 Buyers" />6 Buyers
</label>
<label>
<input type="checkbox" value="7 Buyers" />7 Buyers
</label>
<label>
<input type="checkbox" value="8 Buyers" />8 Buyers
</label>
</div>
try this one. is it ok? if not then tell me what's wrong.
if you have a group of checkbox then you can find all selected checkbox.
$('div').find('input[type=checkbox]:checked').length;
If you only need the number
var count = $scope.selectedSharedBuyerObjectList.reduce(function(sum, item) {
return (item.select) ? sum + 1 : sum;
}, 0);
If you need the filtered array
var selected = $scope.selectedSharedBuyerObjectList.filter(function(item) {
return item.select;
});
var count = selected.length;
Or do it using plain old loop
var count = 0;
for (i = 0; i < $scope.selectedSharedBuyerObjectList.length; i++) {
if ($scope.selectedSharedBuyerObjectList.select) count++;
}
Does anyone know what's wrong with start1()? I know that something is not right but I just can't figure what is it.
I have got this school project where i need to do a quiz and record the time that people need to answer all the questions. I've tried everything i know but nothing works. please help
<body>
<div id="classic">
<input type="button" onclick="start1= setInterval(contador, 1000)" value="yes">
<input type="button" onclick="back1()" value="Menu">
</div>
<div id="quizr" hidden>
<h1> who sings the song </h1>
<div id="P1">
<p>1.'Thinking Out Loud'</p>
A)<input type="radio" name="q1" id="q1r1" > Hozier<br>
B)<input type="radio" name="q1" id="q1r2" > Jason Derulo<br>
C)<input type="radio" name="q1" id="q1r3" > Ed Sheeran<br>
D)<input type="radio" name="q1" id="q1r4" > Mr. Probz<br>
<br>
<input type="button" onclick='go1()' value="next »" >
</div>
<div id="P2" hidden>
<p>2.'GANGNAM STYLE'</p>
A)<input type="radio" name="q15" id="q15r1" > Tori Kelly<br>
B)<input type="radio" name="q15" id="q15r2" > Jessie J<br>
C)<input type="radio" name="q15" id="q15r3" > Beyoncé<br>
D)<input type="radio" name="q15" id="q15r4" > Psy<br>
<br>
<input type="button" onclick='verify1= clearInterval(start1)'value="submit">
</div>
</div>
<div id="result" hidden></div>
function start1()
{
document.getElementById("classic").hidden=true;
document.getElementById("quizr").hidden=false;
}
var t= 0;
function contador()
{
document.getElementById("resultado").innerHTML = ++t;
}
function go1()
{
document.getElementById("P1").hidden= true;
document.getElementById("P2").hidden = false;
}
function verify1()
{
document.getElementById("P2").hidden = true;
document.getElementById("result").hidden = false;
var correctAnswers= 0;
var question1 = document.getElementById("q1r3").checked;
if (question1 === true)
{
correctAnswers = correctAnswers + 1;
}
var question2 = document.getElementById("q2r4").checked;
if (question2 === true)
{
correctAnswers = correctAnswers + 1;
}
document.getElementById("resultado").innerHTML = correctAnswers + "/15" + " " + " correct" + " "+ "answers";
}
This is just a readonly. See the docs:
hidden
Is a Boolean attribute indicates that the element is not yet, or is no longer, relevant. For example, it can be used to hide elements of the page that can't be used until the login process has been completed. The browser won't render such elements. This attribute must not be used to hide content that could legitimately be shown.
What you must really do is:
document.getElementById("classic").style.display = 'none';
document.getElementById("quizr").style.display = 'block';
I'm creating a mini quiz, if the answer is correct the background will be green, if is wrong will be red
here is the code of HTML
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form class="forma">
<div class="pyetja"><h3>1. The flag if Italy which color has..</h3>
<div class="formafoto"><div class="foto"></div><div class="pergjigjet"><div class="pergjigje">
<div class="pergjigjemajtas">
white and blue
</div>
<div class="pergjigjedjathtas" id="0">
<label><input type="radio" value="1" name="0" unchecked="">right</label>
<label><input type="radio" value="0" name="0" unchecked="">wrong</label>
</div>
</div>
<div class="pergjigje">
<div class="pergjigjemajtas">
white and red
</div>
<div class="pergjigjedjathtas" id="1">
<label><input type="radio" value="1" name="1" unchecked="">right</label>
<label><input type="radio" value="0" name="1" unchecked="">wrong</label>
</div>
</div>
<div class="pergjigjeno">
<div class="pergjigjemajtas">
white red and green
</div>
<div class="pergjigjedjathtas" id="2">
<label><input type="radio" value="1" name="2" unchecked="">right</label>
<label><input type="radio" value="0" name="2" unchecked="">wrong</label>
</div>
</div></div></div></div>
<div class="question">
<input id="buton" type="button" value="Finish!" onClick="getScore(this.form); getResult(this.form);">
<p> <strong class="bgclr">Result = </strong><strong><input class="bgclr1" type="text" size="2" name="percentage" disabled></strong><br><br>
<div id="rezultati"></div>
</div>
</form>
</body>
</html>
and javascript
// Insert number of questions
var numQues = 3;
// Insert number of choices in each question
var numChoi = 2;
// Insert number of questions displayed in answer area
var answers = new Array(2);
// Insert answers to questions
answers[0] = 1;
answers[1] = 1;
answers[2] = 1;
// Do not change anything below here ...
function getScore(form) {
var score = 0;
var currElt;
var currSelection;
for (i=0; i<numQues; i++) {
currElt = i*numChoi;
for (j=0; j<numChoi; j++) {
currSelection = form.elements[currElt + j];
if (currSelection.checked) {
if (currSelection.value == answers[i]) {
score++;
}
}
}
}
var radio1 = document.getElementByName("0").value;
if (answers[0] == radio1) {
document.getElementById("0").style.backgroundColor="#00FF00";
} else {
document.getElementById("0").style.backgroundColor="#e83f3f";
}
if(score > 3) {
document.getElementById("rezultati").innerHTML = "Congratulation!";
} else {
document.getElementById("rezultati").innerHTML = "Try again!";
}
form.percentage.value = score;
form.solutions.value = correctAnswers;
}
// End -->
</script>
I get always red background and if the answer is correct, maybe document.getElementByName("0").value is not getting a number to make true the condition
var radio1 = document.getElementByName("0").value;
if (answers[0] == radio1) {
document.getElementById("0").style.backgroundColor="#00FF00";
} else {
document.getElementById("0").style.backgroundColor="#e83f3f";
}
var radio1 = document.getElementByName("0").value;
if (answers[0] == radio1) {
Probably your error is in this line of code, the id="0" is a div and you are trying to get the value of it, this might result into undefined and the value answer[0] is 1, thus 1 is not equal to radio1, thus it is always getting into the else block.
I got the following Javascript code that works properly in Mozilla Firefox but it doesn't in Google Chrome. Any ideea why it will do that?
totalBMI in Chrome even if the value is 45(checking all the last buttons will give you the value 45 which is bigger then 26 so the result should be setting the hRisk div to display:-inline instead of display:none, as the function changeCss() does.) it still consider it to be 0, cause it displays the low risk message. In Firefox, it always displays the right answer.
Javascript code :
function CalculateValue() {
var age = +getAgeValue('age'),
bmi = +getBmiValue('bmi'),
fami = +getFamValue('fam'),
diet = +getDietValue('diet'),
totalBMI = age + bmi + fami + diet;
totalBMI = parseFloat(totalBMI);
alert(totalBMI);
if (totalBMI > 26) {
function changeCSS() {
document.getElementById("btn").onclick = function() {
var hMessage = document.getElementById("hRisk");
hMessage.style.display = 'inline';
/*var newSpan = document.createElement("span");
var newSpanText = document.createTextNode("Your main factors risk are " );
newSpan.appendChild(newSpanText);
var pElem = document.getElementById("space");
pElem.appendChild(newSpan); */
}
}
changeCSS();
} else if (totalBMI > 16 ) {
function changeCSS() {
document.getElementById("btn").onclick = function() {
var mMessage = document.getElementById("mRisk");
mMessage.style.display = 'inline';
}
}
changeCSS();
} else {
function changeCSS() {
document.getElementById("btn").onclick = function() {
var lMessage = document.getElementById("lRisk");
lMessage.style.display = 'inline';
}
}
changeCSS();
}
}
function getAgeValue()
{
for (var i = 0; i < document.getElementsByName('age').length; i++)
{
if (document.getElementsByName('age')[i].checked)
{
return document.getElementsByName('age')[i].value;
}
}
}
function getBmiValue()
{
for (var i = 0; i < document.getElementsByName('bmi').length; i++)
{
if (document.getElementsByName('bmi')[i].checked)
{
return document.getElementsByName('bmi')[i].value;
}
}
}
function getFamValue()
{
for (var i = 0; i < document.getElementsByName('fam').length; i++)
{
if (document.getElementsByName('fam')[i].checked)
{
return document.getElementsByName('fam')[i].value;
}
}
}
function getDietValue()
{
for (var i = 0; i < document.getElementsByName('diet').length; i++)
{
if (document.getElementsByName('diet')[i].checked)
{
return document.getElementsByName('diet')[i].value;
}
}
}
HTML code:
<script src="jsbmi4.js"></script>
<title>Java</title>
<body>
<form method="post" action="process.php" id="radioForm">
<fieldset>
<div>
<label for="age" class="lClass"> <span class="span1"> How old are you? </span>
<input type="radio" id="age1" name="age" value="0">0-25
<input type="radio" id="age1" name="age" value="5">26-40
<input type="radio" id="age1" name="age" value="8">41-60
<input type="radio" id="age1" name="age" value="10">60+
</label>
</div>
<div>
<label for="bmi"> <span class="span1"> What is your BMI? </span>
<input type="radio" id="bmi1" name="bmi" value="0">0-25
<input type="radio" id="bmi1" name="bmi" value="0">26-30
<input type="radio" id="bmi1" name="bmi" value="9">31-35
<input type="radio" id="bmi1" name="bmi" value="10">35+
</label>
</div>
<div>
<label for="fam"> <span class="span1"> Does anybody in your family have diabetes? </span>
<input type="radio" id="fam1" name="fam" value="0">No
<input type="radio" id="fam1" name="fam" value="7">Grandparent
<input type="radio" id="fam1" name="fam" value="15">Sibling
<input type="radio" id="fam1" name="fam" value="15">Parent
</label>
</div>
<div>
<label for="diet"> <span class="span1"> How would you describe your diet? </span>
<input type="radio" id="diet1" name="diet" value="0">Low sugar
<input type="radio" id="diet1" name="diet" value="0">Normal sugar
<input type="radio" id="diet1" name="diet" value="7">Quite high sugar
<input type="radio" id="diet1" name="diet" value="10">High sugar
</label>
</div>
<div class="button">
<input id="btn" type="button" value="Calculate" onclick="CalculateValue()">
<!-- <input id="submit" type"submit" value="submit"> -->
</div>
</fieldset>
</form>
<div id="lRisk">
<h2> Your Result </h2>
<p> Your results show that you currently have a low risk of developing diabetes. However, it is important that you maintain a healty lifestyle in terms of diet and exercise. </p>
</div>
<div id="mRisk">
<h2> Your Result </h2>
<p> Your results show that you currently have a medium risk of developing diabetes. For more information on your risk factors, and what to do about them, please visit our diabetes advice website at http://www.zha.org.zd. </p>
</div>
<div id="hRisk">
<h2> Your Result </h2>
<p>Your results show that you currently have a HIGH risk of developing diabetes.<span id="space"></span> We advice that you contact the Health Authority to discuss your risk factors as soon as you can. Please fill in our contact form and a member of the Health Authority Diabetes Team will be in contact with you. </p>
</div>
</body>
Only modification that I had to do is delete the function changeCSS() and just add what was inside in the if statement.
Thanks Fuximus Foe.
JSCode is here.
function getAgeValue()
{
for (var i = 0; i < document.getElementsByName('age').length; i++)
{
if (document.getElementsByName('age')[i].checked)
{
return document.getElementsByName('age')[i].value;
}
}
}
function getBmiValue()
{
for (var i = 0; i < document.getElementsByName('bmi').length; i++)
{
if (document.getElementsByName('bmi')[i].checked)
{
return document.getElementsByName('bmi')[i].value;
}
}
}
function getFamValue()
{
for (var i = 0; i < document.getElementsByName('fam').length; i++)
{
if (document.getElementsByName('fam')[i].checked)
{
return document.getElementsByName('fam')[i].value;
}
}
}
function getDietValue()
{
for (var i = 0; i < document.getElementsByName('diet').length; i++)
{
if (document.getElementsByName('diet')[i].checked)
{
return document.getElementsByName('diet')[i].value;
}
}
}
function CalculateValue() {
var age = +getAgeValue('age'),
bmi = +getBmiValue('bmi'),
fami = +getFamValue('fam'),
diet = +getDietValue('diet'),
totalBMI = age + bmi + fami + diet;
totalBMI = parseFloat(totalBMI);
alert(totalBMI);
if (totalBMI > 26) {
document.getElementById("btn").onclick = function() {
var hMessage = document.getElementById("hRisk");
hMessage.style.display = 'inline';
/*var newSpan = document.createElement("span");
var newSpanText = document.createTextNode("Your main factors risk are " );
newSpan.appendChild(newSpanText);
var pElem = document.getElementById("space");
pElem.appendChild(newSpan); */
}
} else if (totalBMI > 16 ) {
document.getElementById("btn").onclick = function() {
var mMessage = document.getElementById("mRisk");
mMessage.style.display = 'inline';
}
} else {
document.getElementById("btn").onclick = function() {
var lMessage = document.getElementById("lRisk");
lMessage.style.display = 'inline';
}
}
}
You have not closed any input tags consider using <input ... /> self closing tags. You have misplaced closing </label> tags.
You shouldn't redeclare a function just to use on the next line.
Not sure, why you're binding to onclick event when you already have the answer, that makes it work only when the user hits the calculate button twice.
After fiddling around with this, removing the the changeCSS functions and just executing their code straight away fixes the problem. This is because in Chrome is grabbing the first definition of the function regardless whether the cursor reaches it or not, thus executing only the first changeCSS function on all three cases; firefox reads the correct definition.
JAVASCRIPT:
function CalculateValue() {
var totalBMI = 0+parseInt(getAgeValue('age'))
+parseInt(getBmiValue('bmi'))
+parseInt(getFamValue('fam'))
+parseInt(getDietValue('diet'));
alert(totalBMI);
if (totalBMI > 26) {
//function changeCSS(){
//document.getElementById("btn").onclick = function () {
var hMessage = document.getElementById("hRisk");
hMessage.style.display = 'block';
/*var newSpan = document.createElement("span");
var newSpanText = document.createTextNode("Your main factors risk are " );
newSpan.appendChild(newSpanText);
var pElem = document.getElementById("space");
pElem.appendChild(newSpan); */
//}
//}
//changeCSS();
} else if (totalBMI > 16) {
//function changeCSS(){
//document.getElementById("btn").onclick = function () {
var mMessage = document.getElementById("mRisk");
mMessage.style.display = 'block';
//}
//}
//changeCSS();
} else {
//function changeCSS(){
//document.getElementById("btn").onclick = function () {
var lMessage = document.getElementById("lRisk");
lMessage.style.display = 'block';
//}
//}
//changeCSS();
}
}
function getAgeValue() {
for (var i = 0; i < document.getElementsByName('age').length; i++) {
if (document.getElementsByName('age')[i].checked) {
return document.getElementsByName('age')[i].value;
}
}
return 0;
}
function getBmiValue() {
for (var i = 0; i < document.getElementsByName('bmi').length; i++) {
if (document.getElementsByName('bmi')[i].checked) {
return document.getElementsByName('bmi')[i].value;
}
}
return 0;
}
function getFamValue() {
for (var i = 0; i < document.getElementsByName('fam').length; i++) {
if (document.getElementsByName('fam')[i].checked) {
return document.getElementsByName('fam')[i].value;
}
}
return 0;
}
function getDietValue() {
for (var i = 0; i < document.getElementsByName('diet').length; i++) {
if (document.getElementsByName('diet')[i].checked) {
return document.getElementsByName('diet')[i].value;
}
}
return 0;
}
HTML:
<body>
<form method="post" action="process.php" id="radioForm">
<fieldset>
<div>
<label for="age" class="lClass"><span class="span1"> How old are you?</span></label>
<input type="radio" id="age1" name="age" value="0"/>0-25
<input type="radio" id="age1" name="age" value="5"/>26-40
<input type="radio" id="age1" name="age" value="8"/>41-60
<input type="radio" id="age1" name="age" value="10"/>60+
</div>
<div>
<label for="bmi"> <span class="span1"> What is your BMI? </span></label>
<input type="radio" id="bmi1" name="bmi" value="0"/>0-25
<input type="radio" id="bmi1" name="bmi" value="0"/>26-30
<input type="radio" id="bmi1" name="bmi" value="9"/>31-35
<input type="radio" id="bmi1" name="bmi" value="10"/>35+
</div>
<div>
<label for="fam"> <span class="span1"> Does anybody in your family have diabetes?</span></label>
<input type="radio" id="fam1" name="fam" value="0"/>No
<input type="radio" id="fam1" name="fam" value="7"/>Grandparent
<input type="radio" id="fam1" name="fam" value="15"/>Sibling
<input type="radio" id="fam1" name="fam" value="15"/>Parent
</div>
<div>
<label for="diet"> <span class="span1"> How would you describe your diet? </span></label>
<input type="radio" id="diet1" name="diet" value="0"/>Low sugar
<input type="radio" id="diet1" name="diet" value="0"/>Normal sugar
<input type="radio" id="diet1" name="diet" value="7"/>Quite high sugar
<input type="radio" id="diet1" name="diet" value="10"/>High sugar
</div>
<div class="button">
<input id="btn" type="button" value="Calculate" onclick="CalculateValue()"/>
<!-- <input id="submit" type"submit" value="submit"> -->
</div>
</fieldset>
</form>
<div id="lRisk" style="display:none;">
<h2> Your Result </h2>
<p> Your results show that you currently have a low risk of developing diabetes. However, it is important that you maintain a healty lifestyle in terms of diet and exercise. </p>
</div>
<div id="mRisk" style="display:none;">
<h2> Your Result </h2>
<p> Your results show that you currently have a medium risk of developing diabetes. For more information on your risk factors, and what to do about them, please visit our diabetes advice website at http://www.zha.org.zd. </p>
</div>
<div id="hRisk" style="display:none;">
<h2> Your Result </h2>
<p>Your results show that you currently have a HIGH risk of developing diabetes.<span id="space"></span> We advice that you contact the Health Authority to discuss your risk factors as soon as you can. Please fill in our contact form and a member of the Health Authority Diabetes Team will be in contact with you. </p>
</div>
</body>
and the JSFiddle: http://jsfiddle.net/kWyx8/