In the last tutorial we looked at the code to create a BMI calculator. Our aim was to show you a JavaScript project with some real world application to bring together everything we have learned so far. This Post will look at breaking down the code and explaining the sections, to enable you to reuse the code or adapt all sections of it to your own end.
Example:
Lets get started:
The first section is to create the HTML form on the page, first, take a look at the code below:
<form> <input id="weight" onclick="JavaScript:this.value ='' " onblur="JavaScript:if(this.value ==''){this.value ='Your Weight(Kg)'} " size="27" type="text" value="Your Weight(Kg)" /> <input id="height" onclick="JavaScript:this.value ='' " onblur="JavaScript:if(this.value ==''){this.value ='Your Height(Meters)'} " size="27" type="text" value="Your Height(Meters)" /> </form> <button onclick="JavaScript: calc()">Get BMI</button>
This is a Basic HTML form with two input fields, the difference is we are using some basic JavaScript to manipulate the forms pre-filled cue content.
For example: The form displays the words “Your Weight(Kg)” when the page loads giving cues to the user of what to enter in the field. When the user then clicks into the form the pre-filled content is removed. If the user clicks out of the form but does not enter a value, the form knows to repopulate the field with the pre-selected content “Your Weight(Kg)”.
This is achieved by the use of the onclick and onblur events (all lowercase for XHTML compliance). Lets take look at each:
onclick:
onclick="JavaScript:this.value ='' "
This section shows the event “onclick” triggering some inline JavaScript. We always start the statement with” JavaScript:” to tell the browser what language our inline script is in, then we follow that with the actual JavaScript. In this case we target “this”, being the item that was clicked – and then assign its value to an empty string; this is defined by two single quotes with nothing between them. This whole onclick statement is wrapped in two double quotes, meaning you need to be careful not to include any double quotes in your inline script.
NOTE: This methods is only acceptable for very short scripts – I would say that the script used on the below, onblur, example is the longest script you should be writing in this inline fashion – anything greater than this should be written in external script files.
onblur:
onblur="JavaScript:if(this.value ==''){this.value ='Your Weight(Kg)'} "
The onblur statement is slightly more complicated, it uses a JavaScript conditional statement, only allowing the value to be changed back to “Your Weight(Kg)” if the value “onblur ” is equal to an empty string, again represented by two single quotes.
NOTE: The conditional statement uses the condition == meaning “is equal to” (We will cover conditionals in more depth in a later tutorial).
The next tutorial will continue with the break down of the BMI calculator.