Javascript - Help Displaying Calculations in Calorie Calculator [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am a first year programming student, so I am sorry if this questions seems a little nooby.
I have created a Calorie Calculator and am having an issue displaying the end result (how many calories they need to take in/let out to reach their desired weight). Also, I apologize for the inline CSS, please ignore it. Any help would be greatly appreciated!
EDIT: Added HTML,JS snippet (sorry about that!). I am still having issues with getting the end result to display.
//var weight = document.getElementById("weight").value;
function getCalc() {
var weight = document.querySelector('.weight');
//var height = document.getElementById("height").value;
var height = document.querySelector('.height');
//var age = document.getElementById("age").value;
var age = document.querySelector('.weight');
//var goalweight = document.getElementById("goalweight").value;
var goalweight = document.querySelector('.goalweight');
//var gender = document.getElementById("gender").value;
var gender = document.querySelector('.gender');
//var activity = document.getElementById("activity").value;
var activity = document.querySelector('.activity');
var BMR = " ";
var BMRGoal = " ";
var dailyCalories = " ";
var goalCalories = " ";
if (gender == "male") {
BMR = 66.47+(6.24*weight)+(12.7*height)-(6.755*age);
BMRGoal = 66.47+(6.24*goalweight)+(12.7*height)-(6.755*age);
} else {
BMR = 655.1+(4.35*weight)+(4.7*height)-(4.7*age);
BMRGoal = 66.47+(6.24*goalweight)+(12.7*height)-(6.755*age);
}
if (activity == "none") {
dailyCalories = BMR*1.2;
goalCalories = BMRGoal*1.2;
} else if (activity == 'light') {
dailyCalories = BMR*1.375;
goalCalories = BMRGoal*1.2;
} else if (activity == 'moderate') {
dailyCalories = BMR*1.55;
goalCalories = BMRGoal*1.2;
} else if (activity == 'heavy') {
dailyCalories = BMR*1.725;
goalCalories = BMRGoal*1.2;
} else if (activity == 'xheavy') {
dailyCalories = BMR*1.9;
goalCalories = BMRGoal*1.2;
}
document.getElementByClassName('requireddailycals').innerHTML = 'Your current daily calorie intake is ' + dailyCalories + '. In order to reach your desired weight goal, you will need to increase your caloric intake to ' + goalCalories + '.';
document.getElementById("requireddailycals").value = dailyCalories(goalCalories);
}
<!DOCTYPE html>
<html>
<head>
<title>Nutrition Calculator</title>
<style>
body {
background-color:rgba(102,143,74, 0.3);
}
a {
text-decoration:none;
}
.calcalc_box {
position:absolute;
margin:auto;
top:35vh;
transform:translateY(-35%);
left:50vw;
transform:translateX(-50%);
border:0.2vw solid #a6b727;
text-align:center;
padding:5vw;
font-family:Arial;
box-shadow:0.5vw 0.5vh 0 #a6b727;
}
.calcalc_box > h1 {
font-family:Lucida Console;
color:#316886;
font-size:3vw;
}
.calcalc_box > h2 {
color:#a6b727;
margin:5vh 0 5vh 0;
}
.calcalc_logo {
margin:auto;
}
.calcalc_button {
background-color:#a6b727;
color:black;
padding:0.8vw;
font-size:1.3vw;
font-weight:bold;
border:0.2vw solid #a6b727;
margin:0.5vw;
display:inline-block;
border-radius:0.3vw;
}
.calcalc_button:hover {
background-color:rgba(102,143,74, 0.3);
}
label {
display:inline;
color:#a6b727;
font-weight:bold;
}
.the_calculator {
border:0.2vw solid #a6b727;
text-align:left;
padding:0.5vw;
}
.calculator_section {
display:inline-block;
margin:1vw 0 1vw 0;
width:100%;
}
.calculator_section > label {
font-weight:bold;
padding:0.5vw;
}
.calculator_input {
padding:0.5vw;
margin-bottom:2vw;
}
.calcalc_back {
color:#a6b727;
font-weight:bold;
padding:2vw;
}
</style>
</head>
<body>
<div class="calcalc_box">
<img src="calcalc.png" width="250" height="250" />
<h1>Cal-Calc</h1>
<h2>Nutrition Calculator</h2>
<form class="the_calculator">
<div class="calculator_section">
<label for="gender">Gender</label>
Male<input type="radio" name="gender" value="Male" id="gender">
Female<input type="radio" name="gender" value="Female" id="gender">
</div>
<label for="age">Age : </label><input type="number" name="age" class="calculator_input" id="age"><br>
<label for="height">Height (in inches) : </label><input type="number" name="height" class="calculator_input" id="height"><br>
<label for="weight">Weight (in pounds) : </label><input type="number" name="weight" class="calculator_input" id="weight"><br>
<label for="goalweight">Goal Weight : </label><input type="number" name="weight" class="calculator_input" id="goalweight"><br>
<label for="activity">Activity Level</label>
Little to no exercise <input type="radio" name="activity" value="none" id="activity">
Light Exercise (walks, runs) <input type="radio" name="activity" value="light" id="activity">
Moderate Exercise (sports) <input type="radio" name="activity" value="moderate" id="activity">
Heavy Exercise (daily consistent routine) <input type="radio" name="activity" value="heavy" id="activity">
Extra Heavy Exercise (twice daily consistent routine) <input type="radio" name="activity" value="xheavy" id="activity">
<br><br>
<button class="calcalc_button" onClick="getCalc()" style="margin-left:13vw;" >Calculate
</button>
<span class= "requireddailycals"></span>
</form>
<span class="calcalc_back"><br><br><br>click here to go back</span>
</div>
<script src="./project.js">
</script>
</body>
</html>

In your HTML you have:
<span class= "requireddailycals"/span>
Try instead:
<span class= "requireddailycals"></span>
Then change the JS this way:
document.getElementsByClassName("requireddailycals")[0].innerHTML = 'Your current daily calorie intake is ' + dailyCalories + '. In order to reach your desired weight goal, you will need to increase your caloric intake to ' + goalCalories + '.';
or better, get the element by id
NB: try to use the JS/HTML/CSS snipped to allow use to run your code more easily.

I used an eventListener() with preventDefault(). You can also add a type="button" to your calculate button if you continue to use an inline HTML event attributes but that is not recommended.
I also changed your querySelector because you were attempting to select an element by id, and you were using a class as a selector.
You also had a minor typo, which did not break your code.
This will solve your problem:
document.querySelector('.calcalc_button').addEventListener('click', function(e) {
e.preventDefault();
var weight = document.getElementById('weight').value;
var height = document.getElementById("height").value;
var age = document.getElementById("age").value;
var goalweight = document.getElementById("goalweight").value;
var gender = document.getElementById("gender").value;
var activity = document.getElementById("activity").value;
var BMR = " ";
var BMRGoal = " ";
var dailyCalories = " ";
var goalCalories = " ";
if (gender == "male") {
BMR = 66.47+(6.24*weight)+(12.7*height)-(6.755*age);
BMRGoal = 66.47+(6.24*goalweight)+(12.7*height)-(6.755*age);
} else {
BMR = 655.1+(4.35*weight)+(4.7*height)-(4.7*age);
BMRGoal = 66.47+(6.24*goalweight)+(12.7*height)-(6.755*age);
}
if (activity == "none") {
dailyCalories = BMR*1.2;
goalCalories = BMRGoal*1.2;
} else if (activity == 'light') {
dailyCalories = BMR*1.375;
goalCalories = BMRGoal*1.2;
} else if (activity == 'moderate') {
dailyCalories = BMR*1.55;
goalCalories = BMRGoal*1.2;
} else if (activity == 'heavy') {
dailyCalories = BMR*1.725;
goalCalories = BMRGoal*1.2;
} else if (activity == 'xheavy') {
dailyCalories = BMR*1.9;
goalCalories = BMRGoal*1.2;
}
document.querySelector('.requireddailycals').innerHTML = 'Your current daily calorie intake is ' + dailyCalories + '. In order to reach your desired weight goal, you will need to increase your caloric intake to ' + goalCalories + '.';
//document.getElementById("requireddailycals").value = dailyCalories(goalCalories);
})
//var weight = document.getElementById("weight").value;
function getCalc() {
preventDefault();
console.log("asd");
}
body {
background-color:rgba(102,143,74, 0.3);
}
a {
text-decoration:none;
}
.calcalc_box {
position:absolute;
margin:auto;
top:35vh;
transform:translateY(-35%);
left:50vw;
transform:translateX(-50%);
border:0.2vw solid #a6b727;
text-align:center;
padding:5vw;
font-family:Arial;
box-shadow:0.5vw 0.5vh 0 #a6b727;
}
.calcalc_box > h1 {
font-family:Lucida Console;
color:#316886;
font-size:3vw;
}
.calcalc_box > h2 {
color:#a6b727;
margin:5vh 0 5vh 0;
}
.calcalc_logo {
margin:auto;
}
.calcalc_button {
background-color:#a6b727;
color:black;
padding:0.8vw;
font-size:1.3vw;
font-weight:bold;
border:0.2vw solid #a6b727;
margin:0.5vw;
display:inline-block;
border-radius:0.3vw;
}
.calcalc_button:hover {
background-color:rgba(102,143,74, 0.3);
}
label {
display:inline;
color:#a6b727;
font-weight:bold;
}
.the_calculator {
border:0.2vw solid #a6b727;
text-align:left;
padding:0.5vw;
}
.calculator_section {
display:inline-block;
margin:1vw 0 1vw 0;
width:100%;
}
.calculator_section > label {
font-weight:bold;
padding:0.5vw;
}
.calculator_input {
padding:0.5vw;
margin-bottom:2vw;
}
.calcalc_back {
color:#a6b727;
font-weight:bold;
padding:2vw;
}
<div class="calcalc_box">
<img src="https://placekitten.com/200/300" width="250" height="250" />
<h1>Cal-Calc</h1>
<h2>Nutrition Calculator</h2>
<form class="the_calculator">
<div class="calculator_section">
<label for="gender">Gender</label>
Male<input type="radio" name="gender" value="Male" id="gender">
Female<input type="radio" name="gender" value="Female" id="gender">
</div>
<label for="age">Age : </label><input type="number" name="age" class="calculator_input" id="age"><br>
<label for="height">Height (in inches) : </label><input type="number" name="height" class="calculator_input" id="height"><br>
<label for="weight">Weight (in pounds) : </label><input type="number" name="weight" class="calculator_input" id="weight"><br>
<label for="goalweight">Goal Weight : </label><input type="number" name="weight" class="calculator_input" id="goalweight"><br>
<label for="activity">Activity Level</label>
Little to no exercise <input type="radio" name="activity" value="none" id="activity">
Light Exercise (walks, runs) <input type="radio" name="activity" value="light" id="activity">
Moderate Exercise (sports) <input type="radio" name="activity" value="moderate" id="activity">
Heavy Exercise (daily consistent routine) <input type="radio" name="activity" value="heavy" id="activity">
Extra Heavy Exercise (twice daily consistent routine) <input type="radio" name="activity" value="xheavy" id="activity">
<br><br>
<button class="calcalc_button" style="margin-left:13vw;" >Calculate</button>
<span class= "requireddailycals"></span>
</form>
<span class="calcalc_back"><br><br><br>click here to go back</span>
</div>

Related

Is there a good way to have it so that when someone clicks a button, say option 3 on a scale of 1-5, that it would change the color of buttons 1-3?

I am coding a survey page for a client and they want it so that if someone selects "3" out of a 5 button question scale that buttons 1-3 have a green backgroun...4 would have 1-4, etc.
Currently, if you click a button from the number scale only the one you click is highlighted green. What I want to have is so that it changes the background color of all buttons leading up to the one clicked (If you click 2 then it would change the 1 and 2 buttons to green).
Any help appreciated
Main code for the survey here (1 button example- the rest follow the same format):
<section class="l-reviews pt-30 pb-15">
<div class="contain">
<div class="row">
<div class="col-md-12">
<div class="reviews-wrapper">
<div class="reviews-top-header">
<p id="">Thank you for taking part. Please complete this survey to let us know how we’re
doing.</p>
<p>Please rate the following on a 1-5 scale (1 = Least, 5 = Most)</p>
</div>
<div class="reviews-body">
<form method='post' name='front_end' action="">
<div class="form-control">
<p>1. Were the payroll process and benefits options explained to you fully?</p>
<div class="input-holder">
<input type='hidden' name='title' value='' />
<input type='hidden' name='email' value='' />
<input type="radio" data='Unsatisfied' name='satisfaction' value='20' id='sat-1' /><label for="sat-1"></label>
<input type="radio" data='Not Very Satisfied' name='satisfaction' value='40' id='sat-2' /><label for="sat-2"></label>
<input type="radio" data='Neutral' name='satisfaction' value='60' id='sat-3' /><label for="sat-3"></label>
<input type="radio" data='Satisfied' name='satisfaction' value='80' id='sat-4' /><label for="sat-4"></label>
<input type="radio" data='Highly Satisfied' name='satisfaction' value='100' id='sat-5' /><label for="sat-5"></label>
<div class="error">
<p>Please select at least one option.</p>
</div>
</div>
</div>
<button type="button" class="send-btn">Submit</button>
<input type="hidden" name="action" value="review" />
</form>
<div class='success-form'>
<h3>Your review was submitted successfully</h3>
</div>
</div>
CSS for one button:
input[type=radio]:not(.regular-radio) {
display: none;
}
#wr-1+label,
#application-rating-1+label,
#goals-rating-1+label,
#refer-rating-1+label,
#sat-1+label {
background: url('/wp-content/themes/theme52950/images/reviews-faces/button-1.png');
height: 55px;
width: 109px;
display: inline-block;
padding: 0 0 0 0px;
background-repeat: no-repeat;
}
#wr-1:checked+label,
#application-rating-1:checked+label,
#goals-rating-1:checked+label,
#refer-rating-1:checked+label,
#sat-1:checked+label {
background: url('/wp-content/themes/theme52950/images/reviews-faces/1-hover.png');
height: 55px;
width: 109px;
display: inline-block;
padding: 0 0 0 0px;
background-repeat: no-repeat;
}
JavaScript:
<script>
$(document).ready(function() {
console.log(emailsArray);
$('input[type=radio]').click(function() {
avgOne = parseInt($('input[name=satisfaction]:checked').val());
avgTwo = parseInt($('input[name=working_rating]:checked').val());
avgThree = parseInt($('input[name=application_rating]:checked').val())
avgFour = parseInt($('input[name=goals_rating]:checked').val())
avgFive = parseInt($('input[name=refer_rating]:checked').val())
avgOfAll = ((avgOne + avgTwo + avgThree + avgFour + avgFive) / 5);
if (avgOfAll < 80) {
$('.addtl-comments').show();
} else {
$('.addtl-comments').hide();
}
})
if (checkOne && checkTwo && checkThree && checkFour && checkFive && addtlComments && checkEmailExist && emailNotDupe) {
$('.reviews-body form').submit();
const portalId = '3112753';
const formId = '23212b77-0a27-4833-93a9-766bdf8c3a9b';
const url = 'https://api.hsforms.com/submissions/v3/integration/submit/' + portalId + '/' + formId;
const body = {
context: {
pageUri: window.location.href,
pageName: $(document).find("title").text()
},
fields: [{
name: 'email',
value: getUrlParameter('email')
}, {
name: 'how_satisfied_are_you_with_the_overall_experience_in_working_with_',
value: document.querySelector('input[name="satisfaction"]:checked').getAttribute('data')
}, {
name: 'how_would_you_rate_working_with_your_recruiter_',
value: document.querySelector('input[name="working_rating"]:checked').getAttribute('data')
}, {
name: 'how_would_you_rate_the_application_process_',
value: document.querySelector('input[name="application_rating"]:checked').getAttribute('data')
}, {
name: 'how_satisfied_were_you_with_communication_throughout_your_interview_process_',
value: document.querySelector('input[name="goals_rating"]:checked').getAttribute('data')
}, {
name: 'how_likely_would_you_be_to_recommend_to_other_candidates_',
value: document.querySelector('input[name="refer_rating"]:checked').getAttribute('data')
}]
};
Any help appreciated.
A minimal reproducable example would have been sufficient. Just for fun: here's an idea for you:
document.addEventListener(`click`, handle);
function handle(evt) {
if (evt.target.dataset.scoreid) {
const score = +evt.target.dataset.scoreid;
const stars = document.querySelectorAll(`[data-scoreid]`)
.forEach((el, i) =>
el.classList[i <= score ? `add` : `remove`](`starred`));
const rateEl = evt.target.closest(`#rate`);
rateEl.classList.remove(`single`, `score`);
rateEl.classList.add(score + 1 === 1 ? `single` : `scored`);
rateEl.dataset.score = score + 1;
}
}
document.body.insertAdjacentHTML(
`beforeEnd`,
`<div id="rate" date-score="0" data-single="0">
${[...Array(5)].map((v, i) => `<span data-scoreid="${i}"></span>`)
.join(``)}
</div>`);
#rate {
font-size: 2rem;
}
#rate.scored:after {
content: 'you scored 'attr(data-score)' stars' ;
color: green;
}
#rate.single:after {
content: 'you scored 'attr(data-score)' star' ;
color: green;
}
#rate span {
cursor: pointer;
}
#rate span:before {
content: '\2606'
}
#rate span.starred:before {
content: '\2605';
color: green;
}

Hide/reset the result every time when I clicked the button jQuery

Hi I have these caculator code, I want to hide the result at the bottom everytime I clicked the "calculate" button on the top, how can I do that? below is my code:
when I clicked on the calculate it should give you result of first box and all the result of the rest box, then you can still change the value from box 2 to box 4, then it will show the final result at the bottom, the issue here is when I go back to the box1 and re-input the value and calculate it, the result at the bottom remain old result, how can I hide it when I re-click the button?? full code see here: https://jsfiddle.net/jackwei/w42yocgv/248/
function calculation() {
var firstValue = document.getElementById("firstValue").value;
var secondValue = document.getElementById("secondValue").value;
var first1Value = document.getElementById("first1Value").value;
var second2Value = document.getElementById("second2Value").value;
var first3Value = document.getElementById("first3Value").value;
var first4Value = document.getElementById("first4Value").value;
var result = document.getElementById("result");
var result2 = document.getElementById("result2");
var result3 = document.getElementById("result3");
var result4 = document.getElementById("result4");
var resultall = document.getElementById("resultall");
var calc = firstValue *3 + secondValue *7 + first1Value *1 + second2Value *3;
var calc2 = (firstValue*1 +first1Value*1)*3 + (secondValue*1+second2Value*1)*5;
var calc3 = firstValue*1 + secondValue*1 + first1Value*1 + second2Value*1;
var calc4 = firstValue*1 + secondValue*1 + first1Value*1 + second2Value*1;;
result.textContent = "Template Build " + calc + " Hours";
result2.textContent = calc2 + " Hours";
result3.textContent = calc3 + " Hours";
result4.textContent = calc4 + " Hours";
resultall.textContent = " Campaign Management " + calc2 + " Hours," + " Deployment " + calc3 + " Hours,"+ " Ongoing " + calc4 + " Hours";
document.getElementById('first3Value').value=parseFloat(firstValue) + parseFloat(first1Value);
document.getElementById('first4Value').value=parseFloat(secondValue) + parseFloat(second2Value);
document.getElementById('first5Value').value=parseFloat(firstValue) + parseFloat(secondValue)+ parseFloat(first1Value)+ parseFloat(second2Value);
document.getElementById('first6Value').value=parseFloat(firstValue) + parseFloat(secondValue)+ parseFloat(first1Value)+ parseFloat(second2Value);
}
$('#first3Value,#first4Value,#first5Value,#first6Value').keyup(function(){ // run anytime the value changes
var first3Value = Number($('#first3Value').val()); // get value of field
var first4Value = Number($('#first4Value').val());
var first5Value = Number($('#first5Value').val());
var first6Value = Number($('#first6Value').val()); // convert it to a floa
$('#result2').html(first3Value*3 + first4Value*5 + "Hours" ); // add them and output it
$('#result3').html(first5Value*1 + "Hours");
$('#result4').html(first6Value*1 + "Hours");
$('#resultbox2').html(first3Value*3 + first4Value*5 + "Hours" );
$('#resultbox3').html(first5Value*1 + "Hours" );
$('#resultbox4').html(first6Value*1 + "Hours" );
});
/* Chrome, Safari, Edge, Opera */
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
/* Firefox */
input[type=number] {
-moz-appearance: textfield;
}
#wrap{
width:400px;
margin:0 auto;
text-align:left;
margin-top:8px;
padding:5px;
padding-bottom:15px;
background:#fff;
font-family:AvenirLTStd, Arial, Helvetica, sans-serif;
font-size:13px;
line-height:16px;
}
#wrap .cont_details fieldset,.cont_order fieldset{
margin:10px;
padding:20px;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
-khtml-border-radius: 10px;
border-radius: 10px;
}
#wrap legend{
font-size:16px;
font-family:Georgia, "Times New Roman", Times, serif;
color:#000;
font-weight:bold;
font-style:italic;
padding-bottom:10px;
}
#wrap .cont_details input{
margin-bottom:10px;
color:#000;
}
#wrap .input1:hover,.input1:active{
}
#wrap label{
display:block;
font-size:12px;
color:#000;
font-weight:bold;
}
#wrap label.inlinelabel
{
display:inline;
}
#wrap .cont_order input{
margin-bottom:5px;
}
#wrap .cont_order p{
padding-top:5px;
}
#wrap input[type="radio"]
{
margin-top:8px;
margin-bottom:8px;
}
#wrap input[type="text"]:hover,
#wrap input[type="text"]:active {
background-color: #FAF398;
}
#wrap input#submit
{
margin:10px;
padding-left:20px;
padding-right:20px;
padding-top:10px;
padding-bottom:10px;
}
.totalPrice
{
padding:10px;
font-weight:bold;
background-color:#ff0;
}
#wrap label.radiolabel
{
font-weight:normal;
display:inline;
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<title>Cake Form</title>
<link href="http://files.javascript-coder.com/calculation/styles/cakeform.css" rel="stylesheet" type="text/css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body onload="hideTotal()">
<div id="wrap">
<div>
<div class="cont_order">
<fieldset>
<legend>Template Build</legend>
<label >New Template Build</label><br><input type="number" id="firstValue" name="firstValue" onclick="calculateTotal()" /> x Simple (3h)<br>
<input type="number" id="secondValue" name="secondValue" onclick="calculateTotal()" />
x Medium (7h)<br>
<br/>
<label >Adaptions of new templates</label>
<br>
<input type="text" id="first1Value" name="first1Value" onclick="calculateTotal()" />
x Simple (1h)<br>
<input type="text" id="second2Value" name="second2Value" onclick="calculateTotal()" />
x Medium (3h)<br/>
<br/>
<p>
<input type="button" id="calc" onclick="calculation()" value="Calculate">
</p>
<div id="result" class="wrap totalPrice"> </div>
</p>
<div id="resultall" class="wrap totalPrice">
</div>
</fieldset>
</div>
<div class="cont_order">
<fieldset>
<legend>Campaign Management</legend>
<label >Campaign Integration</label><br>
<input type="number" id="first3Value" name="first3Value" onclick="calculateTotal()" class="cm">
x Simple (3h)<br>
<p>
<input type="number" id="first4Value" name="first4Value" onclick="calculateTotal()" class="cm"> x Medium (5h)
</p>
<div id="" class="wrap totalPrice"> Total: <span id="result2">
</span></div>
</fieldset>
</div>
<div class="cont_order">
<fieldset>
<legend>Deployment</legend>
<label >Campaign Deployment</label><br>
<input type="number" id="first5Value" name="first5Value" onclick="calculateTotal()" /> x Per section Per Run<br>
<div id="" class="wrap totalPrice"> Total: <span id="result3">
</fieldset>
</div>
<div class="cont_order">
<fieldset>
<legend>Ongoing</legend>
<label >
Continuous Run (non-automated) + Deployment</label><br><input type="text" id="first6Value" name="first6Value" value="0" onclick="calculateTotal()" />
x Per section Per Run<br>
<div id="" class="wrap totalPrice"> Total: <span id="result4">
</fieldset>
</div>
</p>
<div id="" class="wrap totalPrice">
Campaign Management <span id="resultbox2"></span><br> Deployment <span id="resultbox3"></span><br> Ongoing <span id="resultbox4"></span><br> </div>
</div>
</div><!--End of wrap-->
</body>
</html>

Why whenever I am submitting the form its asks for to select male/ female and the form is not getting submitted

function validation() {
var uid = document.registration.userid;
var passid = document.registration.passid;
var uname = document.registration.name;
var uadd = document.registration.address;
var ucountry = document.registration.country;
var uzip = document.registration.zip;
var uemail = document.registration.email;
var umsex = document.registration.sex;
var ufsex = document.registration.sex;
if (userid_validation(uid, 5, 12)) {
if (passid_validation(passid, 7, 12)) {
if (allLetter(uname)) {
if (alphanumeric(uadd)) {
if (countryselect(ucountry)) {
if (allnumeric(uzip)) {
if (ValidateEmail(uemail)) {
if (validsex(umsex, ufsex)) {}
}
}
}
}
}
}
}
return false;
}
function userid_validation(uid, mx, my) {
var uid_len = uid.value.length;
if (uid_len == 0 || uid_len >= my || uid_len < mx) {
alert("User Id should not be empty or length should be between " + mx + " to " + my);
uid.focus();
return false;
}
return true;
}
function passid_validation(passid, mx, my) {
var passid_len = passid.value.length;
if (passid_len == 0 || passid_len >= my || passid_len < mx) {
alert("Password should not be empty or length should be between " + mx + " to " + my);
passid.focus();
return false;
}
return true;
}
function allLetter(uname) {
var letters = /^[A-Za-z ]+$/;
if (uname.value.match(letters)) {
return true;
} else {
alert('Name must have alphabet characters only');
uname.focus();
return false;
}
}
function alphanumeric(uadd) {
var letters = /^[0-9a-zA-Z]+$/;
if (uadd.value.match(letters)) {
return true;
} else {
alert('User address must have alphanumeric characters only');
uadd.focus();
return false;
}
}
function countryselect(ucountry) {
if (ucountry.value == "Default") {
alert('Select your country from the list');
ucountry.focus();
return false;
} else {
return true;
}
}
function allnumeric(uzip) {
var numbers = /^[0-9]+$/;
if (uzip.value.match(numbers)) {
return true;
} else {
alert('ZIP code must have numeric characters only');
uzip.focus();
return false;
}
}
function ValidateEmail(uemail) {
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (uemail.value.match(mailformat)) {
return true;
} else {
alert("You have entered an invalid email address!");
uemail.focus();
return false;
}
}
function validsex(umsex, ufsex) {
x = 0;
if (umsex.checked) {
x++;
}
if (ufsex.checked) {
x++;
}
if (x == 0) {
alert('Select Male/Female');
umsex.focus();
return false;
} else {
alert('Form Successfully Submitted');
window.location.reload()
return true;
}
}
h1 {
margin-left: 400px;
}
form li {
list-style: none;
}
form {
margin-left: 320px;
}
form ul li label {
float: left;
clear: left;
width: 100px;
text-align: right;
margin-right: 10px;
font-size: 18px;
font-weight: bold;
}
form ul li input,
select,
span {
float: left;
margin-bottom: 10px;
}
form textarea {
float: left;
width: 350px;
height: 200px;
}
[type="submit"] {
clear: left;
margin-left: 255px;
margin-top: 20px;
font-size: 18px
}
p {
margin-left: 70px;
font-weight: bold;
}
<!DOCTYPE html>
<html>
<head>
<title> Exercise 4 (Registration Page) </title>
<link rel="stylesheet" href="E4.css">
<script src="E4.js"></script>
</head>
<h1>Registration Form</h1>
<form name='registration' onSubmit="return validation();">
<ul>
<li><label for="userid">User id:</label></li>
<li><input type="text" name="userid" size="12" /></li>
<li><label for="passid">Password:</label></li>
<li><input type="password" name="passid" size="12" /></li>
<li><label for="name">Name:</label></li>
<li><input type="text" name="name" size="50" /></li>
<li><label for="address">Address:</label></li>
<li><input type="text" name="address" size="50" /></li>
<li><label for="country">Country:</label></li>
<li>
<select name="country">
<option selected="" value="Default">(Please select a country)</option>
<option>Australia</option>
<option>Afghanistan</option>
<option>Brazil</option>
<option>China</option>
<option>Canada</option>
<option>Denmark</option>
<option>Egypt</option>
<option>France</option>
<option>Germany</option>
<option>India</option>
<option>Japan</option>
<option>Korea</option>
<option>Madagascar</option>
<option>Malaysia</option>
<option>Nepal</option>
<option>New Zealand</option>
<option>Nigeria</option>
<option>Philippines</option>
<option>Qatar</option>
<option>Russia</option>
<option>Saudi Arabia</option>
<option>Serbia</option>
<option>Singapore</option>
<option>South Africa</option>
<option>Spain</option>
<option>Turkey</option>
<option>USA</option>
<option>Yemen</option>
<option>Zimbabwe</option>
</select>
</li>
<li><label for="zip">ZIP Code:</label></li>
<li><input type="text" name="zip" /></li>
<li><label for="email">Email:</label></li>
<li><input type="text" name="email" size="50" /></li>
<li><label id="gender">Sex:</label></li>
<li><input type="radio" name="sex" value="Male" /><span>Male</span></li>
<li><input type="radio" name="sex" value="Female" /><span>Female</span></li>
<li><label>Language:</label></li>
<li><input type="checkbox" name="en" value="en" checked /><span>English</span></li>
<li><input type="checkbox" name="nonen" value="noen" /><span>Non English</span></li>
<li><label for="desc">About:</label></li>
<li><textarea name="desc" id="desc"></textarea></li>
<li><input type="submit" name="submit" value="Submit" /></li>
</ul>
</form>
<body>
</body>
</html>
After completely filling the form when I click the submit button it shows the radio button validation that is select male or female but its already selected previously and when I click the OK in the alert
all the data I entered gets erased please help.
I have inserted the .js .css and .html file the gender part is in the last section pls check once. I an not getting what went wrong.
couple of minor problems. You need to return true if all tests pass. Also, not sure what registration does but when changed to getElementById it all looks good.
function validation()
{
var uid = document.registration.userid;
var passid = document.registration.passid;
var uname = document.registration.name;
var uadd = document.registration.address;
var ucountry = document.registration.country;
var uzip = document.registration.zip;
var uemail = document.registration.email;
var umsex = document.getElementById('male');
var ufsex = document.getElementById('female');
if(userid_validation(uid,5,12)){
if(passid_validation(passid,7,12)){
if(allLetter(uname)){
if(alphanumeric(uadd)){
if(countryselect(ucountry)){
if(allnumeric(uzip)){
if(ValidateEmail(uemail)){
if(validsex(umsex,ufsex)){
return true;
}
}
}
}
}
}
}
}
return false;
}
function userid_validation(uid,mx,my)
{
var uid_len = uid.value.length;
if (uid_len == 0 || uid_len >= my || uid_len < mx)
{
alert("User Id should not be empty or length should be between "+mx+" to "+my);
uid.focus();
return false;
}
return true;
}
function passid_validation(passid,mx,my)
{
var passid_len = passid.value.length;
if (passid_len == 0 ||passid_len >= my || passid_len < mx)
{
alert("Password should not be empty or length should be between "+mx+" to "+my);
passid.focus();
return false;
}
return true;
}
function allLetter(uname)
{
var letters = /^[A-Za-z ]+$/;
if(uname.value.match(letters))
{
return true;
}
else
{
alert('Name must have alphabet characters only');
uname.focus();
return false;
}
}
function alphanumeric(uadd)
{
var letters = /^[0-9a-zA-Z]+$/;
if(uadd.value.match(letters))
{
return true;
}
else
{
alert('User address must have alphanumeric characters only');
uadd.focus();
return false;
}
}
function countryselect(ucountry)
{
if(ucountry.value == "Default")
{
alert('Select your country from the list');
ucountry.focus();
return false;
}
else
{
return true;
}
}
function allnumeric(uzip)
{
var numbers = /^[0-9]+$/;
if(uzip.value.match(numbers))
{
return true;
}
else
{
alert('ZIP code must have numeric characters only');
uzip.focus();
return false;
}
}
function ValidateEmail(uemail)
{
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(uemail.value.match(mailformat))
{
return true;
}
else
{
alert("You have entered an invalid email address!");
uemail.focus();
return false;
}
}
function validsex(umsex,ufsex){
var x=0;
if(umsex.checked)x++;
if(ufsex.checked)x++;
if(x==0){
alert('Select Male/Female');
umsex.focus();
return false;
}
else
{
alert('Form Successfully Submitted');
return true;}
}
h1 {
margin-left: 400px;
}
form li {
list-style: none;
}
form {
margin-left: 320px;
}
form ul li label{
float: left;
clear: left;
width: 100px;
text-align: right;
margin-right: 10px;
font-size: 18px;
font-weight: bold;
}
form ul li input, select, span {
float: left;
margin-bottom: 10px;
}
form textarea {
float: left;
width: 350px;
height: 200px;
}
[type="submit"] {
clear: left;
margin-left: 255px;
margin-top: 20px;
font-size:18px
}
p {
margin-left: 70px;
font-weight: bold;
}
<!DOCTYPE html>
<html>
<head>
<title> Exercise 4 (Registration Page) </title>
<link rel="stylesheet" href="E4.css">
<script src="E4.js"></script>
</head>
<h1>Registration Form</h1>
<form name='registration' onSubmit="return validation();">
<ul>
<li><label for="userid">User id:</label></li>
<li><input type="text" name="userid" size="12" /></li>
<li><label for="passid">Password:</label></li>
<li><input type="password" name="passid" size="12" /></li>
<li><label for="name">Name:</label></li>
<li><input type="text" name="name" size="50" /></li>
<li><label for="address">Address:</label></li>
<li><input type="text" name="address" size="50" /></li>
<li><label for="country">Country:</label></li>
<li><select name="country">
<option selected="" value="Default">(Please select a country)</option>
<option>Australia</option>
<option>Afghanistan</option>
<option>Brazil</option>
<option>China</option>
<option>Canada</option>
<option>Denmark</option>
<option>Egypt</option>
<option>France</option>
<option>Germany</option>
<option>India</option>
<option>Japan</option>
<option>Korea</option>
<option>Madagascar</option>
<option>Malaysia</option>
<option>Nepal</option>
<option>New Zealand</option>
<option>Nigeria</option>
<option>Philippines</option>
<option>Qatar</option>
<option>Russia</option>
<option>Saudi Arabia</option>
<option>Serbia</option>
<option>Singapore</option>
<option>South Africa</option>
<option>Spain</option>
<option>Turkey</option>
<option>USA</option>
<option>Yemen</option>
<option>Zimbabwe</option>
</select></li>
<li><label for="zip">ZIP Code:</label></li>
<li><input type="text" name="zip" /></li>
<li><label for="email">Email:</label></li>
<li><input type="text" name="email" size="50" /></li>
<li><label id="gender">Sex:</label></li>
<li><input id='male' type="radio" name="sex" value="Male" /><span>Male</span></li>
<li><input id='female' type="radio" name="sex" value="Female" /><span>Female</span></li>
<li><label>Language:</label></li>
<li><input type="checkbox" name="en" value="en" checked /><span>English</span></li>
<li><input type="checkbox" name="nonen" value="noen" /><span>Non English</span></li>
<li><label for="desc">About:</label></li>
<li><textarea name="desc" id="desc"></textarea></li>
<li><input type="submit" name="submit" value="Submit" /></li>
</ul>
</form>
<body>
</body>
</html>

How can I change the content of the modal based on the input of the user

So I've been trying to find a method to display the results of a questionnaire and I tried to use a modal as is looks better than just an alert button, which should display a different piece of information based on the inputs of the user in the questionnaire. I created a few functions which return the values that i want to display in the modal but I don't know how to incorporate them into the modal content. I don't know if that is possible and if not what other methods would you suggest to display the information to the user?
function fn1() {
var score = 2.5;
var bmi1 = document.getElementById("bmi1");
var bmi2 = document.getElementById("bmi2");
var bmi3 = document.getElementById("bmi3");
var contraNo = document.getElementById("contraNo");
var contraOral = document.getElementById("contraOral");
var contraIud = document.getElementById("contraIud");
var hrtNo = document.getElementById("hrtNo");
var hrtConti = document.getElementById("hrtConti");
var hrtNon = document.getElementById("hrtNon");
var diabYes = document.getElementById("diabYes");
var diabNo = document.getElementById("diabNo");
var pcosYes = document.getElementById("pcosYes");
var pcosNo = document.getElementById("pcosNo");
var nulliparity = document.getElementById("nulliparity");
var parOver1 = document.getElementById("parOver1");
if (bmi1.checked == true)
score = score + 0;
else if (bmi2.checked == true)
score = score + 1.85;
else if (bmi3.checked == true)
score = score + 4.675;
else if (bmi4.checked == true)
score = score + 6.175;
if (contraNo.checked == true)
score = score + 0;
else if (contraOral.checked == true)
score = score - 0.8;
else if (contraIud.checked == true)
score = score - 1.2;
if (hrtNo.checked == true)
score = score + 0;
else if (hrtConti.checked == true)
score = score - 0.675;
else if (hrtNon.checked == true)
score = score + 0.5;
if (diabYes.checked == true)
score = score + 1.375;
else if (diabNo.checked == true)
score = score + 0;
if (pcosYes.checked == true)
score = score + 3.75;
else if (pcosNo.checked == true)
score = score + 0;
if (nulliparity.checked == true)
score = score + 1.075;
else if (parOver1.checked == true)
score = score - 0.8;
var percentage = Math.round((score * 100) / 100);
return score;
}
function category() {
var result1 = fn1();
let category;
if (result1 >= 1 && result1 <= 3.5)
category = "low";
//alert("Your risk category is low ");
else if (result1 > 3.5 && result1 <= 6.5)
// alert("Your risk category is medium ");
category = "medium";
else if (result1 > 6.5)
category = "high";
// alert("Your risk category is medium ");
return category;
}
/* function displayResult() {
let category1 = category();
var result = fn1();
alert(result);
alert(category1);
return false;
}*/
document.getElementById("btn1").addEventListener("click",
function() {
document.querySelector(".bg-modal").style.display = 'flex';
});
document.querySelector('.close').addEventListener('click',
function() {
document.querySelector(".bg-modal").style.display = 'none';
});
//incorporate the functions fn1() and category() in the modal
.bg-modal {
width: 500px;
height: 300px;
background-color: rgba(0, 0, 0, 0.3);
position: absolute;
top: 250px;
right: 50%;
left: 50%;
transform: translate(-50%, -50%);
display: flex;
justify-content: center;
align-items: center;
display: none;
}
.modal-content {
width: 500px;
height: 300px;
background-color: skyblue;
border-radius: 10px;
text-align: center;
padding: 20px;
position: relative;
}
.close {
position: absolute;
top: 0;
right: 14px;
font-size: 38px;
transform: rotate(45deg);
cursor: pointer;
}
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="index.css">
</head>
<body>
<h1>Endometrial Cancer Predictor </h1>
<h3>What is your BMI?</h3>
<input id="bmi1" type="radio" name="grp1" value="0"> less than 25 </input> <br>
<input id="bmi2" type="radio" name="grp1" value="1.85"> 25 to 29 </input> <br>
<input id="bmi3" type="radio" name="grp1" value="4.675"> 30 to 39 </input> <br>
<input id="bmi4" type="radio" name="grp1" value="6.175"> over 40 </input>
<h3>Do you take contraception?</h3>
<input id="contraNo" type="radio" name="grp2" value="0"> No <br>
<input id="contraOral" type="radio" name="grp2" value="-0.8"> Oral Contraception <br>
<input id="contraIud" type="radio" name="grp2" value="-1.2"> Intrauterine Device (IUD)
<h3>Do you take HRT?</h3>
<input id="hrtNo" type="radio" name="grp3" value="0"> No <br>
<input id="hrtConti" type="radio" name="grp3" value="-0.675"> Continous <br>
<input id="hrtNon" type="radio" name="grp3" value="0.5"> Non Continous
<h3>Do you suffer from Type 2 Diabetes?</h3>
<input id="diabYes" type="radio" name="grp4" value="1.375"> Yes <br>
<input id="diabNo" type="radio" name="grp4" value="0"> No
<h3>Do you suffer from PCOS?</h3>
<input id="pcosYes" type="radio" name="grp5" value="3.75"> Yes <br>
<input id="pcosNo" type="radio" name="grp5" value="0"> No
<h3>What is your parity?</h3>
<input id="nulliparity" type="radio" name="grp6" value="1.075"> 0 <br>
<input id="parOver1" type="radio" name="grp6" value="-0.8"> +1
<br>
<br>
<button id="btn1" onclick="displayResult()">Submit </button>
<div class="bg-modal">
<div class="modal-content">
<div class="close">+</div>
<script src="index.js"></script>
</body>
</html>
It's not pretty, but this shows you how to get the values from your functions and show them in the modal.
function fn1()
{
var score=2.5;
var bmi1 = document.getElementById("bmi1");
var bmi2 = document.getElementById("bmi2");
var bmi3 = document.getElementById("bmi3");
var contraNo = document.getElementById("contraNo");
var contraOral = document.getElementById("contraOral");
var contraIud = document.getElementById("contraIud");
var hrtNo = document.getElementById("hrtNo");
var hrtConti = document.getElementById("hrtConti");
var hrtNon = document.getElementById("hrtNon");
var diabYes = document.getElementById("diabYes");
var diabNo = document.getElementById("diabNo");
var pcosYes = document.getElementById("pcosYes");
var pcosNo = document.getElementById("pcosNo");
var nulliparity = document.getElementById("nulliparity");
var parOver1 = document.getElementById("parOver1");
if(bmi1.checked==true)
score=score+0;
else if(bmi2.checked==true)
score=score+1.85;
else if(bmi3.checked==true)
score=score+4.675;
else if(bmi4.checked==true)
score=score+6.175;
if(contraNo.checked==true)
score=score+0;
else if(contraOral.checked==true)
score=score-0.8;
else if(contraIud.checked==true)
score=score-1.2;
if(hrtNo.checked==true)
score=score+0;
else if(hrtConti.checked==true)
score=score-0.675;
else if(hrtNon.checked==true)
score=score+0.5;
if(diabYes.checked==true)
score=score+1.375;
else if(diabNo.checked==true)
score=score+0;
if(pcosYes.checked==true)
score=score+3.75;
else if(pcosNo.checked==true)
score=score+0;
if(nulliparity.checked==true)
score=score+1.075;
else if(parOver1.checked==true)
score=score-0.8;
var percentage = Math.round((score *100) /100);
return score;
}
function category()
{
var result1= fn1();
let category;
if (result1>=1 && result1<=3.5)
category= "low";
//alert("Your risk category is low ");
else if (result1>3.5 && result1<=6.5)
// alert("Your risk category is medium ");
category= "medium";
else if (result1>6.5)
category= "high";
// alert("Your risk category is medium ");
return category;
}
/* function displayResult() {
let category1 = category();
var result = fn1();
alert(result);
alert(category1);
return false;
}*/
document.getElementById("btn1").addEventListener("click", function(){
document.querySelector(".bg-modal").style.display = 'flex';
document.getElementById("modal").innerHTML = "fn1: " + fn1() + " Cat:" + category();
});
document.querySelector('.close').addEventListener('click', function(){
document.getElementById("modal").innerHTML = "";
document.querySelector(".bg-modal").style.display = 'none';
});
//incorporate the functions fn1() and category() in the modal
.bg-modal{
width: 500px;
height: 300px;
background-color: rgba(0, 0, 0, 0.3);
position: absolute;
top: 250px;
right: 50%;
left: 50%;
transform: translate(-50%, -50%);
display: flex;
justify-content: center;
align-items: center;
display: none;
}
.modal-content{
width: 500px;
height: 300px;
background-color: skyblue;
border-radius: 10px;
text-align: center;
padding: 20px;
position: relative;
}
.close{
position: absolute;
top: 0;
right: 14px;
font-size: 38px;
transform: rotate(45deg);
cursor: pointer;
}
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="index.css">
</head>
<body>
<h1>Endometrial Cancer Predictor </h1>
<h3>What is your BMI?</h3>
<input id="bmi1" type="radio" name="grp1" value="0">
less than 25 </input> <br>
<input id="bmi2" type="radio" name="grp1" value="1.85">
25 to 29 </input> <br>
<input id="bmi3" type="radio" name="grp1" value="4.675">
30 to 39 </input> <br>
<input id="bmi4" type="radio" name="grp1" value="6.175">
over 40 </input>
<h3>Do you take contraception?</h3>
<input id="contraNo" type="radio" name="grp2" value="0">
No <br>
<input id="contraOral" type="radio" name="grp2" value="-0.8">
Oral Contraception <br>
<input id="contraIud" type="radio" name="grp2" value="-1.2">
Intrauterine Device (IUD)
<h3>Do you take HRT?</h3>
<input id="hrtNo" type="radio" name="grp3" value="0">
No <br>
<input id="hrtConti" type="radio" name="grp3" value="-0.675">
Continous <br>
<input id="hrtNon" type="radio" name="grp3" value="0.5">
Non Continous
<h3>Do you suffer from Type 2 Diabetes?</h3>
<input id="diabYes" type="radio" name="grp4" value="1.375">
Yes <br>
<input id="diabNo" type="radio" name="grp4" value="0">
No
<h3>Do you suffer from PCOS?</h3>
<input id="pcosYes" type="radio" name="grp5" value="3.75">
Yes <br>
<input id="pcosNo" type="radio" name="grp5" value="0">
No
<h3>What is your parity?</h3>
<input id="nulliparity" type="radio" name="grp6" value="1.075">
0 <br>
<input id="parOver1" type="radio" name="grp6" value="-0.8">
+1
<br>
<br>
<button id="btn1" >Submit </button>
<div class="bg-modal">
<div id="modal" class="modal-content">
</div>
<div class="close">+</div>
</div>
<script src="index.js"></script>
</body>
</html>

How to write javascript code for BMI_Calculator.html?

I'm supposed to write javascript code for an html page that will calculate a persons BMI and tell them what it means (the number). The rules of the test were to not change the html on the page, but to just write the javascript code and link it to the html page. That's all. I have copied the html page just in case you guys might wanna have a look at it. Here is what the BMI Calculator is supposed to do using javascript:
Person enters name, selects gender, enters weight and height. The application will calculate the persons BMR, BMI, and tell what it means (i.e. saying "you are too thin", "you are healthy", or "you are overweight").
and it will display an image of a thin, healthy, or overweight person which is a png image.
If they do not enter a name, an error message prompts them to enter a name. The name must be at least five characters long.
If they do not select a gender, then an error message prompts them to please select a gender. The gender is represented by a radio button. The user selects male or female.
If the user does not enter a weight, an error message prompts them to please enter a weight.
If height is not entered, an error message prompts them to please enter a height.
If you are a male, you're BMR is calculated as: BMR = 10*(weight+6.25)(height-5)(age+5).
If you are a female, you're BMR is calculated as: BMR = 10*(weight+6.25)(height-5)(age-161).
If the BMI is less than 18.5: "you are too thin".
If the BMI is between 20 to 25: "you are healthy".
If the BMI is greater than 25: "you are overweight".
Also, please don't put the question on hold or delete it. This is important for me and I need help. If you want help, please don't. It took me a long time to write this question.
Here is the html that I am supposed to write the javascript code for:
<html>
<head>
<title> BMI Calculator </title>
<style>
label {
display: inline-block;
width: 80px;
height: 25px;
}
button {
height:30px;
margin: 5px 0px;
}
fieldset {
display: inline-block;
}
#errMsg {
color: red;
}
#frm {
float: left;
width: 30%;
}
#imgSec {
float: left;
padding: 5px 0px;
border-left: 3px solid darkblue;
}
</style>
<!-- link to javascript file -->
<script type="text/javascript" src="BMI_javascript.js">
</script>
</head>
<body>
<div id="title"><h3>BMI Calculator</h3></div>
<section id="frm">
<form name="bmiForm" onsubmit="return false;">
<fieldset>
<legend>Enter your Details:</legend>
<label for="user">Name:</label>
<input type="text" id="user" size="25" required> <br />
<label for="gender">Gender:</label>
<input type="radio" id="rbMale" name="gender"> Male
<input type="radio" id="rbFemale" name="gender">Female <br />
<label for="age">Age:</label>
<input type="number" id="age" size="10" required> <br />
<label for="weight">Weight(kg):</label>
<input type="number" id="weight" size="10" required> <br />
<label for="height">Height(cm):</label>
<input type="number" id="height" size="10" required> <br />
<div id="errMsg"></div>
</fieldset>
<br>
<button onclick="calculate()">Calculate BMI</button>
<button type="reset" onclick="clearErr()">Reset</button>
<br>
<fieldset>
<legend>Result:</legend>
<label for="bmr">Your BMR: </label>
<input type="text" name="bmr" id="bmr" size="18" readonly><br />
<label for="bmi">Your BMI: </label>
<input type="text" name="bmi" id="bmi" size="10" readonly><br />
<label for="meaning">This Means: </label>
<input type="text" name="meaning" id="meaning" size="25" readonly><br/>
</fieldset>
</section>
<section id="imgSec">
<img id="img" src="" height="250px">
</section>
</form>
</body>
</html>
And here is the javascript I wrote for it. I know it's horrible. The problem is the code does not work. Nothing works.
function GenderType() {
var GenderType = document.getElementsByName("rbMale","rbFemale");
if(rbMale == "Male") {
GenderType.innerHTML = "Male";
} else {
rbFemale == "Female";
GenderType.innerHTML = "Female";
}
}
function validate() {
var name = document.getElementById("name");
var age = document.getElementById("age");
var male = document.getElementById("male");
var female = document.getElementById("female");
var weight = document.getElementById("weight");
var height = document.getElementById("height");
error = false;
var reName = /^[a-zA-Z ]{5,}$/;
if (reName.test(name.value) == false) {
nameError.innerHTML = "Name must be eight letters or more";
error = true;
} else {
nameError.innerHTML = "";
}
age = parseInt(age.value);
if ( isNaN(age) || age < 0 || age > 65) {
ageError.innerHTML = "Age must be in range 0-65";
error = true;
} else {
ageError.innerHTML = "";
}
weight = parseInt(weight.value);
if ( isNaN(weight) || weight < 0) {
weightError.innerHTML = "Weight must be greater than 0";
error = true;
} else {
weightError.innerHTML = "";
}
height = parseInt(height.value);
if (isNaN(height) || height < 0) {
heightError.innerHTML = "height must be greater than 0"
error = true;
} else {
heightError.innerHTML = "";
}
if ( !male.checked & !female.checked) {
genderError.innerHTML = "Select value";
error = true;
} else {
genderError.innerHTML = "";
}
}
function BMRCalculate () {
if ( validate()==false ) {
var GenderType = document.getElementById("rbMale","rbFemale").value;
var age = document.getElementById("age").value;
var female = document.getElementById("rbFemale");
var male = document.getElementById("rbMale");
var weight = document.getElementById("weight");
var height = document.getElementById("height");
var BMIValue = weight/( (height/100)*(height/100) );
var BMRValue;
var ThisMeans = document.getElementById("meaning");
if(GenderType == male) {
BMRValue = 10*(weight+6.25)*(height-5)*(age+5);
} else {
GenderType = female;
BMRValue = 10*(weight+6.25)*(height-5)*(age-161);
}
if (BMIValue<18.5) {
ThisMeans = "you are too thin";
document.write(ThisMeans);
} else if (BMIValue>18.5 && BMIValue<25) {
ThisMeans = "you are healthy";
document.write(ThisMeans);
} else {
ThisMeans = "You are not healthy";
document.write(ThisMeans);
}
}
Mate, #gavgrif gave you some very good tips, but about the code...try to start over and think the problem again.

Categories

Resources