In the last post we looked at JavaScript functions, as well as a couple of ways to call them in your script. In this tutorial we will look at taking your JavaScript to the next level and creating something which is useful for you to reuse, or adapt, for your own web design projects.
We will take two HTML form elements and allow the user to enter their height and weight and use it to calculate the users BMI. Some of the more powerful languages such as PHP or ASP would have ended up being far too complex, with too many page loads and server requests, and with information having to be posted from page to page. This is an example of a small application where JavaScript comes into its element; with front end scripting you are able to do everything on one page, reducing the page reloads for the user and requests on the server. Overall it Keeps the interface faster and slick for the user, without the load on your server.
So without any further delay, lets take a look at the code below. Firstly, the example:
and here is the code, first the HTML:
<form> <input id="weight" onclick="JavaScript:this.value =''" size="27" type="text" value="Your Weight(Kg)" /> <input id="height" onclick="JavaScript:this.value =''" size="27" type="text" value="Your Height(Meters)" /> </form> <button onclick="JavaScript: calc()">Get BMI</button>
Now, the JavaScript:
function calc() { var weight = document.getElementById('weight').value; var height = document.getElementById('height').value; var BMI = (weight)/(height*height); actualresult(BMI); } function actualresult(bmi) { if(bmi < 20) { alert("Your BMI is (approx):"+Math.round(bmi)+" you are under weight"+" \n \n*********!!!PLEASE NOTE!!!******* \n \n this information was referenced from weightlossresources.co.uk/ this is an example JavaScript tutorial and should not be used to calulate your actual BMI"); } else if(bmi <25) { alert("Your BMI is (approx):"+Math.round(bmi)+" you are a normal weight"+" \n \n*********!!!PLEASE NOTE!!!******* \n \n this information was referenced from weightlossresources.co.uk/ this is an example JavaScript tutorial and should not be used to calulate your actual BMI"); } else if (bmi <30) { alert("Your BMI is (approx):"+Math.round(bmi)+" you are overweight"+" \n \n*********!!!PLEASE NOTE!!!******* \n \n this information was referenced from weightlossresources.co.uk/ this is an example JavaScript tutorial and should not be used to calulate your actual BMI"); } else if (bmi >30) { alert("Your BMI is (approx):"+Math.round(bmi)+" you are Obese"+" \n \n*********!!!PLEASE NOTE!!!******* \n \n this information was referenced from weightlossresources.co.uk/ this is an example JavaScript tutorial and should not be used to calulate your actual BMI"); } }
In the next post we will break down the code and explain how we have combined all the different aspects together to create this mini JavaScript app.