Jquery result display issue - javascript

I am trying to create a bmi calculator and tried the following .
$(document).ready(function() {
// Convert ft to inches
function convertHeight(ft) {
return ft * 12;
}
// calculate total height
function showbmi() {
var weight = document.getElementById('weight').value * 1;
var height_ft = document.getElementById('height_ft').value * 1;
var height_in = document.getElementById('height_in').value * 1;
var height = convertHeight(height_ft) + height_in;
var female_h = (height * height) / 30;
var male_h = (height * height) / 28;
var gender;
var x = document.getElementsByName("gender");
for (var i = 0; i < x.length; i++) {
if (x[i].checked == true) {
gender = x[i].value;
break;
}
}
var bmi = "?";
if (gender == "female") {
bmi = (Math.round((weight * 703) / (height * height)));
if (isNaN(bmi)) bmi = "?";
} else {
bmi = (Math.round((weight * 703) / (height * height)));
if (isNaN(bmi)) bmi = "?";
}
var bmi_msg = "?";
if (bmi < 15) {
bmi_msg = "Very severely underweight";
} else if (bmi <= 16) {
bmi_msg = "Severely underweight";
} else if (bmi <= 18.4) {
bmi_msg = "Underweight";
} else if (bmi <= 24.9) {
bmi_msg = "Normal";
} else if (bmi <= 29.9) {
bmi_msg = "Overweight";
} else if (bmi <= 34.9) {
bmi_msg = "Obese Class I (Moderately obese)";
} else if (bmi <= 39.9) {
bmi_msg = "Obese Class II (Severely obese)";
} else {
bmi_msg = "Obese Class III (Very severely obese)";
}
$("#result").text(bmi);
return bmi;
$("#comment").text(bmi_msg);
return bmi_msg;
}
//bmi infos
//finish
$("form#calc input").bind("keydown", function() {
setTimeout(function() {
showbmi();
}, 100);
return true;
});
$("form#calc input").bind("change", function() {
showbmi();
});
$("form#calc radio").bind("change", function() {
showbmi();
});
$("form#calc").bind("submit", function() {
showbmi();
return false;
});
});
The bmi displays correctly, but the messages forbmi values are not displaying. i checked the console and it says code unreachable.
Can somebody throw some light where I am goin wrong, and How I can improve this code.

You have a return statement after setting the result content before setting the comment, so $("#comment").text(bmi_msg); is never executed.
A function will return control to the caller method as soon as a return statement is executed, so there should be only one return statement in an execution flow.
So remove return bmi; from the code for the comment setting to work
$(document).ready(function() {
// Convert ft to inches
function convertHeight(ft) {
return ft * 12;
}
// calculate total height
function showbmi() {
var weight = $('#weight').val() * 1;
var height_ft = $('#height_ft').val() * 1;
var height_in = $('#height_in').val() * 1;
var height = convertHeight(height_ft) + height_in;
var female_h = (height * height) / 30;
var male_h = (height * height) / 28;
var gender = $('input[name="gender"]:checked').val();
var bmi = "?";
if (gender == "female") {
bmi = (Math.round((weight * 703) / (height * height)));
if (isNaN(bmi)) bmi = "?";
} else {
bmi = (Math.round((weight * 703) / (height * height)));
if (isNaN(bmi)) bmi = "?";
}
var bmi_msg = "?";
if (bmi < 15) {
bmi_msg = "Very severely underweight";
} else if (bmi <= 16) {
bmi_msg = "Severely underweight";
} else if (bmi <= 18.4) {
bmi_msg = "Underweight";
} else if (bmi <= 24.9) {
bmi_msg = "Normal";
} else if (bmi <= 29.9) {
bmi_msg = "Overweight";
} else if (bmi <= 34.9) {
bmi_msg = "Obese Class I (Moderately obese)";
} else if (bmi <= 39.9) {
bmi_msg = "Obese Class II (Severely obese)";
} else {
bmi_msg = "Obese Class III (Very severely obese)";
}
$("#result").text(bmi);
$("#comment").text(bmi_msg);
return bmi;
}
//bmi infos
var timer;
$("#calc input").bind("keydown change", function() {
clearTimeout(timer);
timer = setTimeout(function() {
showbmi();
}, 100);
return true;
});
$("#calc").bind("submit", function() {
clearTimeout(timer);
showbmi();
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="calc">
<input id="weight" />
<input id="height_ft" />
<input id="height_in" />
<br />
<input name="gender" type="radio" value="male" />
<input name="gender" type="radio" value="female" />
<br />
<input type="submit" value="Check" />
<div id="result"></div>
<div id="comment"></div>
</form>
Note: Since you are using jQuery, why not use its utility methods to get/set the values/content

Related

missing ; before statement error on google Script

I try my first steps in google script and I try to calculate the percentile of a given range of numbers in a row. I always got a
Missing ; before statement. (line 107, file "Sitan_Code") error
I don't see the point, why I get this.
could anybody help?
Thanks in advance
function percentile() {
var tenPercent = 10 / 100; //simsSheet.getRange("I5").getValue() / 100;
var twentyfivePercent = 25 / 100; //simsSheet.getRange("I6").getValue() / 100;
var fiftyPercent = 50 / 100; //simsSheet.getRange("I7").getValue() / 100;
var seventyfivePercent = 75 / 100; //simsSheet.getRange("I8").getValue()/ 100;
var neintyPercent = 90 / 100; // simsSheet("I9").getValue() / 100;
var values = simsSheet.getRange("A1:NTP1").getValues().sort();
var percentage = [tenPercent, twentyfivePercent, fiftyPercent, seventyfivePercent, neintyPercent];
for (i = 0; i < percentage.length; i++) {
var index = values.length * percentage[i];
if ((index % 2) === 0) {
var average = (index[i] + index[i + 1]) / 2;
if (percentage[i] == percentage[tenPercent]) {
var ten = simsSheet.getRange("K5") set.Value(average);
} else if (percentage[i] == percentage[twentyfivePercent]) {
var twentyfive = simsSheet.getRange("K6").setValue(average);
} else if (percentage[i] == percentage[fiftyPercent]) {
var fivty = simsSheet.getRange("K7").setValue(average);
} else if (percentage[i] == percentage[seventyfivePercent]) {
var seventyfive = simsSheet.getRange("K8").setValue(average);
} else if (percentage[i] == percentage[neintyPercent] {
var neinty = simsSheet.getRange("K9").setValue(average);
else {
inx = Math.round(index);
}
Your code seems to be missing a few braces and periods that causes the compilation to fail, refer to the version below:
function percentile() {
var tenPercent = 10 / 100; //simsSheet.getRange("I5").getValue() / 100;
var twentyfivePercent = 25 / 100; //simsSheet.getRange("I6").getValue() / 100;
var fiftyPercent = 50 / 100; //simsSheet.getRange("I7").getValue() / 100;
var seventyfivePercent = 75 / 100; //simsSheet.getRange("I8").getValue()/ 100;
var neintyPercent = 90 / 100; // simsSheet("I9").getValue() / 100;
var values = simsSheet.getRange("A1:NTP1").getValues().sort();
var percentage = [tenPercent, twentyfivePercent, fiftyPercent, seventyfivePercent, neintyPercent];
for (i = 0; i < percentage.length; i++) {
var index = values.length * percentage[i];
if ((index % 2) === 0) {
var average = (index[i] + index[i + 1]) / 2;
if (percentage[i] == percentage[tenPercent]) {
var ten = simsSheet.getRange("K5").setValue(average);
} else if (percentage[i] == percentage[twentyfivePercent]) {
var twentyfive = simsSheet.getRange("K6").setValue(average);
} else if (percentage[i] == percentage[fiftyPercent]) {
var fivty = simsSheet.getRange("K7").setValue(average);
} else if (percentage[i] == percentage[seventyfivePercent]) {
var seventyfive = simsSheet.getRange("K8").setValue(average);
} else if (percentage[i] == percentage[neintyPercent]) {
var neinty = simsSheet.getRange("K9").setValue(average);
} else {
inx = Math.round(index);
}
}
}
}

How do I use objects in JavaScript

I need help integrating classes and functions into an HTML page using JavaScript. I am not sure how to properly create an object and call its function(i.e.)
function calculateGrade(){
var x1 = document.forms["myForm"]["fname"].value;
var x2 = document.forms["myForm"]["lname"].value;
var x3 = document.forms["myForm"]["hwork"].value;
var x4 = document.forms["myForm"]["awork"].value;
var x5 = document.forms["myForm"]["midscore"].value;
var x6 = document.forms["myForm"]["midgrade"].value;
var x7 = document.forms["myForm"]["finscore"].value;
var x8 = document.forms["myForm"]["fingrade"].value;
var p1 = new Student(
x1,x2,[x3],[x4],x5,x6,x7,x8
); //creates it
document.getElementById("myForm").style.visibility="hidden";
document.getElementById("text").style.visibility="hidden";
alert(p1.getGrade()); //calls one of its methods
return false;
}
I am also unsure how to properly use classes in JS. I want the classes to be private while the methods are privileged.
function Student(){
function Student(firstName,lastName,hScore,aScore,mScore,mGrade,fScore,fGrade){
this.firstName = firstName;
this.lastName = lastName;
this.homework = new Coursework();
this.inClass = new Coursework();
this.studentsFinal = new Exam(fScore,fGrade);
this.studentsMidterm = new Exam(mScore,mGrade);
var that = this;
function setMidterm(mScore, mGrade){
that.studentsMidterm = new Exam(mScore, mGrade);
}
this.setMidterm = function() { // privileged method
setMidterm(mScore, mGrade);
}
function setFinal( fScore, fGrade){
that.studentsFinal = new Exam(fScore, fGrade);
}
this.setFinal = function() { // privileged method
setFinal( fScore, fGrade);
}
function addGradedHomework(hScore){
that.homework.addScore(hScore);
}
this.addGradedHomework = function() { // privileged method
addGradedHomework(hScore);
}
function addGradedActivity(aScore){
that.inClass.addScore(aScore);
}
this.addGradedActivity = function() { // privileged method
addGradedActivity(aScore);
}
this.printGrade=printGrade;
function getGrade(){
var letterGrade;
var weightCourse = ( (that.inClass.meanScore() * .15) + (that.homework.meanScore() * .25) + (that.studentsMidterm.getExamScore() * .25) + (that.studentsFinal.getExamScore() * .35) );
if (that.studentsMidterm.getExamScore() >= that.studentsFinal.getExamScore() && that.studentsMidterm.getExamScore() >= weightCourse)
letterGrade = studentsFinal.getExamGrade();
else if (that.studentsFinal.getExamScore() >= that.studentsMidterm.getExamScore() && that.studentsMidterm.getExamScore() >= weightCourse)
letterGrade = that.studentsFinal.getExamGrade();
else{
if (90.00 <= weightCourse){
letterGrade = "A";
}
else if( 80 <= weightCourse && weightCourse < 90){
letterGrade = "B";
}
else if (70 <= weightCourse && weightCourse < 80){
letterGrade = "C";
}
else if (60 <= weightCourse && weightCourse < 70){
letterGrade = "D";
}
else{
letterGrade = "F";
}
}
return letterGrade;
}
this.getGrade = function() { // privileged method
getGrade();
}
}
}
function Coursework(){
var sumScore;
var numScore;
function addScore(score){
numScore++;
if (score > 100)
sumScore = sumScore + 100;
else if ( score < 0)
sumScore = sumScore + 0;
else
sumScore = sumScore + score;
}
function meanScore(){
if (numScore == 0){
return 0.0;
}
else{
return (sumScore / numScore);
}
}
}
function Exam() {
var examScore;
var examGrade;
function Exam(score,grade ){
if (examScore < 0){
examScore = 0;
}
else if (examScore > 100){
examScore = 100;
}
else {
examScore = score;
}
switch (grade) {
case "A":
examGrade = "A";
break;
case "B":
examGrade = "B";
break;
case "C":
examGrade = "C";
break;
case "D":
examGrade = "D";
break;
case "F":
examGrade = "F";
break;
default:
examGrade = "F";
}
}
function getExamScore(){
return examScore;
}
function getExamGrade(){
return examGrade;
}
}
Any help is appreciated. If this does not make since let me know, I wasn't quite sure how to word it.
<html>
<title> Assignment 7 </title>
<h1> Students's Assignment 7 </h1>
<head>
<script type="text/javascript">
function calculateGrade(){
var x1 = document.forms["myForm"]["fname"].value;
var x2 = document.forms["myForm"]["lname"].value;
var x3 = document.forms["myForm"]["hwork"].value;
var x4 = document.forms["myForm"]["awork"].value;
var x5 = document.forms["myForm"]["midscore"].value;
var x6 = document.forms["myForm"]["midgrade"].value;
var x7 = document.forms["myForm"]["finscore"].value;
var x8 = document.forms["myForm"]["fingrade"].value;
var p1 = new Student(
x1,x2,[x3],[x4],x5,x6,x7,x8
);
//console.log(p1.getGrade());
//alert(x1);
document.getElementById("myForm").style.visibility="hidden";
document.getElementById("text").style.visibility="hidden";
alert(p1.getGrade());
return false;
}
function Student(){
function Student(firstName,lastName,hScore,aScore,mScore,mGrade,fScore,fGrade){
this.firstName = firstName;
this.lastName = lastName;
this.homework = new Coursework();
this.inClass = new Coursework();
this.studentsFinal = new Exam(fScore,fGrade);
this.studentsMidterm = new Exam(mScore,mGrade);
var that = this;
function setMidterm(mScore, mGrade){
that.studentsMidterm = new Exam(mScore, mGrade);
}
this.setMidterm = function() { // privileged method
setMidterm(mScore, mGrade);
}
function setFinal( fScore, fGrade){
that.studentsFinal = new Exam(fScore, fGrade);
}
this.setFinal = function() { // privileged method
setFinal( fScore, fGrade);
}
function addGradedHomework(hScore){
that.homework.addScore(hScore);
}
this.addGradedHomework = function() { // privileged method
addGradedHomework(hScore);
}
function addGradedActivity(aScore){
that.inClass.addScore(aScore);
}
this.addGradedActivity = function() { // privileged method
addGradedActivity(aScore);
}
this.printGrade=printGrade;
function getGrade(){
var letterGrade;
var weightCourse = ( (that.inClass.meanScore() * .15) + (that.homework.meanScore() * .25) + (that.studentsMidterm.getExamScore() * .25) + (that.studentsFinal.getExamScore() * .35) );
if (that.studentsMidterm.getExamScore() >= that.studentsFinal.getExamScore() && that.studentsMidterm.getExamScore() >= weightCourse)
letterGrade = studentsFinal.getExamGrade();
else if (that.studentsFinal.getExamScore() >= that.studentsMidterm.getExamScore() && that.studentsMidterm.getExamScore() >= weightCourse)
letterGrade = that.studentsFinal.getExamGrade();
else{
if (90.00 <= weightCourse){
letterGrade = "A";
}
else if( 80 <= weightCourse && weightCourse < 90){
letterGrade = "B";
}
else if (70 <= weightCourse && weightCourse < 80){
letterGrade = "C";
}
else if (60 <= weightCourse && weightCourse < 70){
letterGrade = "D";
}
else{
letterGrade = "F";
}
}
return letterGrade;
}
this.getGrade = function() { // privileged method
getGrade();
}
}
}
function Coursework(){
var sumScore;
var numScore;
function addScore(score){
numScore++;
if (score > 100)
sumScore = sumScore + 100;
else if ( score < 0)
sumScore = sumScore + 0;
else
sumScore = sumScore + score;
}
function meanScore(){
if (numScore == 0){
return 0.0;
}
else{
return (sumScore / numScore);
}
}
}
function Exam() {
var examScore;
var examGrade;
function Exam(score,grade ){
if (examScore < 0){
examScore = 0;
}
else if (examScore > 100){
examScore = 100;
}
else {
examScore = score;
}
switch (grade) {
case "A":
examGrade = "A";
break;
case "B":
examGrade = "B";
break;
case "C":
examGrade = "C";
break;
case "D":
examGrade = "D";
break;
case "F":
examGrade = "F";
break;
default:
examGrade = "F";
}
}
function getExamScore(){
return examScore;
}
function getExamGrade(){
return examGrade;
}
}
</script>
</head>
<body bgcolor="#81F79F">
<b id="text">Enter you information below</b>
<form id="myForm" onsubmit="return calculateGrade();" >
First name: <br><input type="text" id="element_1_1" name="fname"><br>
Last name: <br><input type="text" id="element_1_2" name="lname"><br>
Homework: <br><input type="text" id="element_1_3" name="hwork"><br>
Activity: <br><input type="text" id="element_1_4" name="awork"><br>
Midterm Score: <br><input type="text" id="element_1_5" name="midscore"><br>
Midterm Grade: <br><input type="text" id="element_1_6" name="midgrade"><br>
Final Score: <br><input type="text" id="element_1_7" name="finscore"><br>
Final Grade: <br><input type="text" id="element_1_8" name="fingrade"><br>
<input type="submit" value="Submit">
</form>
<div id="stuff"></div>
</body>
</html>

Javascript: Many conditions but different actions

I'm creating a BMI calculator.
This is my code so far:
var $ = function(id) {
return document.getElementById(id);
}
var calculateBmi = function() {
var weight = parseInt($("weight").value);
var height = parseInt($("height").value);
if (weight > 0 && height > 0 && weight !=isNaN && height !=isNaN){
var bmi = Math.floor((weight / (height * height)) * 703);
$("bmi_message").innerHTML = "" + bmi;
}
if (bmi > 18.5) {
$("bmi_message").innerHTML = ": Underweight";
}
else if (bmi >= 18.5 && bmi <= 24.9) {
$("bmi_message").innerHTML = ": Normal";
}
else if (bmi >= 25 && bmi <= 29) {
$("bmi_message").innerHTML = ": Overweight";
}
else if (bmi > 30) {
$("bmi_message").innerHTML = ": Obese";
}
else if (isNaN(weight)) {
$("weight_message").innerHTML = "Enter numerical weight value (lbs)";
}
else if (isNaN(height)) {
$("height_message").innerHTML = "Enter numerical height value (kg)";
}
}
window.onload = function () {
$("calculateBmi").onclick = calculateBmi;
}
I have all these conditions (bmi > x OR bmi < x) that require different actions. Each range should result in a different text being displayed in my span element, however this is not happening. Could someone explain to me what is wrong and maybe provide me with better practices?
In your code
if (bmi > 18.5) {
$("bmi_message").innerHTML = ": Underweight";
}
will always be true for any value higher than 18.5 so you wont get any other value but always Underweight.
Try
if (bmi < 18.5) {
$("bmi_message").innerHTML = ": Underweight";
}
This only points out a third particular issue in your code. You are checking if weight (and height) are numbers with weight != isNaN, but:
100 != isNaN // --> true
'text' != isNaN // --> true
isNaN isn't a static value but a function to use like so:
var weight = 100; isNaN(weight) // -->false
!isNaN(weight) // --> true
var height = 'text'; isNaN(height) // --> true
!isNaN(height) // --> false
You should consider all three answers here together to get the right code.

javascript price calculator rounding results from x,1 -> x+1

I've no clue what I'm doing wrong.
I've to code an price calculator but that's not the problem, it's working.
My Problem is, that if for example it calculates the number 4,3 it has to go further with the number 5 and so on.
But in my Calculator is still by the number 4
<script type="text/javascript">
function getPrice() {
var size = Math.floor(document.getElementsByName('tarpaulin-height')[0].value * document.getElementsByName('tarpaulin-width')[0].value);
var value = 'Preis nur auf Anfrage';
var price = 154;
if (size <= 20) {
if (size > 4) {
if (size > 19) {
size = 20;
}
else if (size > 18) {
size = 19;
}
else if (size > 17) {
size = 18;
}
else if (size > 16) {
size = 17;
}
else if (size > 15) {
size = 16;
}
else if (size > 14) {
size = 15;
}
else if (size > 13) {
size = 14;
}
else if (size > 12) {
size = 13;
}
else if (size > 11) {
size = 12;
}
else if (size > 10) {
size = 11;
}
else if (size > 9) {
size = 10;
}
else if (size > 8) {
size = 9;
}
else if (size > 7) {
size = 8;
}
else if (size > 6) {
size = 7;
}
else if (size > 5) {
size = 6;
}
else if (size > 4) {
size = 5;
}
price += (size - 4) * 7.9;
}
value = price.toFixed(2).replace('.', ',') + ' €';
}
document.getElementsByName('price')[0].value = value;
console.log(size)
}
</script>
thank you!

addEventListener onClick not working

I don't know what's wrong with my code, but when I use addEventListener() it doesn't do a thing.
Does anyone have another solution so that I can bind the #ibm button ID to compute() onClick event?
I plan to run this on Firfox OS, so setting an onClick attribute on the button itself is prohibited as stated on the CSP Violations.
function compute()
{
var w = parseInt(document.getElementById('weight').value);
var hf = parseInt(document.getElementById('height_ft').value);
var hi = parseInt(document.getElementById('height_in').value);
if (!checker(w))
{
showAndroidToast('Please input your weight');
return;
}
else if (!checker(hf))
{
showAndroidToast('Please input your height');
return;
}
if (!checker(hi))
{
var i = 0;
document.getElementById('height_in').value = i;
}
else
{
var i = parseInt(document.getElementById('height_in').value);
}
var comp_h = parseFloat((hf * 12) + (i * 1));
var tot_h = comp_h * comp_h;
comp = formula(w, tot_h);
document.getElementById('bmitot').value = comp;
if (comp > 30)
{
document.getElementById('res').value = 'Severe Level! Thats too much FAT! Go get some diet pills or something!';
document.getElementById("bmitot").style.backgroundColor = "red";
document.getElementById("zero").style.visibility = "hidden";
document.getElementById("one").style.visibility = "hidden";
document.getElementById("two").style.visibility = "hidden";
document.getElementById("three").style.visibility = "visible";
}
if (comp > 25 && comp <=29.9)
{
document.getElementById('res').value = 'Bad Level! You are too FAT!';
document.getElementById("bmitot").style.backgroundColor = "yellow";
document.getElementById("zero").style.visibility = "hidden";
document.getElementById("one").style.visibility = "hidden";
document.getElementById("two").style.visibility = "visible";
document.getElementById("three").style.visibility = "hidden";
}
if (comp > 18.5 && comp <=24.9)
{
document.getElementById('res').value = 'Nice! You are on the safe level!';
document.getElementById("bmitot").style.backgroundColor = "green";
document.getElementById("zero").style.visibility = "hidden";
document.getElementById("one").style.visibility = "visible";
document.getElementById("two").style.visibility = "hidden";
document.getElementById("three").style.visibility = "hidden";
}
if (comp < 18.5)
{
document.getElementById('res').value = 'Bad Level! Go get some nutrients!';
document.getElementById("bmitot").style.backgroundColor = "yellow";
document.getElementById("zero").style.visibility = "visible";
document.getElementById("one").style.visibility = "hidden";
document.getElementById("two").style.visibility = "hidden";
document.getElementById("three").style.visibility = "hidden";
}
}
function formula(w, h)
{
var bmi = w/h * 703;
var a_bmi = Math.floor(bmi);
var dif = bmi - a_bmi;
dif = dif * 10;
diff = Math.round(dif);
if (dif == 10)
{
a_bmi += 1;
dif = 0;
}
bmi = a_bmi + "." + diff;
return bmi;
}
function checker(type)
{
if (isNaN(parseInt(type)))
{
return false;
}
else if (type < 0)
{
return false;
}
else
{
return true;
}
}
function showAndroidToast(toast)
{
Android.showToast(toast);
}
document.getElementById('ibm').addEventListener('click', compute);
Your code is executing fine and compute function is triggering fine. There may be an issue with the code in execute function. Check this fiddle

Categories