Skip to content

4. Taking this to JavaScript.

Helen Burgess edited this page Apr 8, 2016 · 5 revisions

Now it is time for us to look at taking some of our solutions and creating them into JavaScript. The solutions will be in another Branch of this code.

a good exercise is to create a Form page to have the input when you need to READ in variable values or use the prompt() function in JavaScript.

Example - Add three numbers

 <!DOCTYPE html>
 <html>
<head lang="en">
	<title>Simple Program Design</title>
	<script type="text/javascript" src="scripts.js"></script>
</head>
<body onload="result()">
	
	<main id="output">

	<p id='result'>Result is: </p>
	</form>
	</main>
	
</body>
 </html>

JavaScript may look something like this when using the prompt function. As the prompt function only stores characters I have made sure that the input is change to a number so it can be added. This is the parseInt() function.

 var result = function (){

var num1 = prompt('please enter your first number');
var num2 = prompt('please enter your second number');
var num3 = prompt('please enter your third number');
var totalNum = 0;

//to make sure input is a number
num1 = parseInt(num1);
num2 = parseInt(num2);
num3 = parseInt(num3);

totalNum = num1 + num2 + num3;

outputLine(totalNum);

 }

 //declaring functions for html output
 function outputLine(line) {
  //manipulating the DOM of the browser

   var output = document.getElementById('result'); //finding the element to be manipulated
    
   var currentHtml = output.innerHTML; //assigning current text value of element 

   var newHtml = currentHtml + ' <strong>'+ line + '</strong>'; //creating new text value for element

   output.innerHTML = newHtml; //writing the new text.

 }

Now see what you can do with the Fahrenheit conversion to Celsius conversion exercise.

Clone this wiki locally