Client side web programming


Javascript practice 2a: User input

The following program asks for user data as input, and places the data into a variable. Values of variables can be changed in the program by different mathematical operations. Placing a new value to var2:

var2 = var1 + 7

The "equal to" sign means here "set the value".
Write a small script that makes currency transformations. First the script declares a variable called "money", asks how much the user wants to change, and then places that value for the variable "money".

var money = prompt("How many euros do you want exchange into francs?");

after that the result needs to be calculated (create variable "francs"). Finally, an alert box tells the result

alert( "You get " + francs + " francs")

Practice 2b: Temperature conversion

This script performs temperature conversions from Fahrenheit to Celsius.

<title>Temperature converter by NN </title>

<h1> Scripts: Temperature converter </h1>
<h2>Author: your name </h2>
Input Farhrenheit degrees
<input type="text" id="fahrBox" size="8" value=" " />
<input type="button" value="Calculate in Celsius"
onClick="tempinF = document.getElementById('fahrBox').value;
tempinF = parseFloat(tempinF);
tempinC = (5/9)*(tempinF-32);
document.getElementById('celsiusBox').value=tempinC; "/>

Temperature in Celsius: <input type="text" id="celsiusBox" size="8" value=" " /> </form>


Save this and try. The function parseFloat checks the input and transforms it to a number. Sometimes the input is interpreted as a string, which is avoided this way.

Next task is to do the conversion back. Remember that an id must always be unique. You cannot have same id's for different items. The formula is
tempinF = ((9/5)*tempinC)+32.

Practice 2c: Adding some choice

In this exercise we use several Javascript functions:

Math.random generates a random number between 0 and 1.

Math.floor drops decimals from the number

Exclamation mark ! is the logical NOT operation.

If -statement allows you to test a condition and branch to different courses of action. Use again the HTML template and add the following to script to the head section:

function weather_comment()
if ( !Math.random ) // here you call a standard function
document.write('<pre> -- weather called off due to rain --</pre>');
else if ( Math.floor((Math.random()*2)) == 0 )
document.write("<strong>It's just awful.</strong>\n");
document.write("<em>How wonderful it is!</em>\n");

In the body section add:

<P>Weather report for today:</P>
<p>End of report.</p>

Now test this and try reloading the page.

Practice 2d: checking user input

Create a new page where you test user input. Accept only input that is a valid number. Create a form that ask when the user woke up:

When did you wake up? :
You need three input fields. The name attribute of the form is name="timepoint". Name the other input fields accordingly name="hoursBox" and name="minsBox". Add a size attribute for both, with a value 2. The button gets action onclick='alert("OK clicked!");'. Test your form.

In order to do the checking, add a script to the button :

<input type="button" value="Update"
var hours =
if (hours < 1 || hours > 12) {
alert("Give a value in range 1 to 12.");
// to inform about a valid value
alert("The hours " + hours + " are fine.");

ParsInt takes the input value and converts it to an integer. If the user inputs 11.53, JavaScript parseInt converts it to 11. Similarily, extra letters are removed, such as 5des is converted by parseInt to 5.
"return" at the end of the function stops its execution if user input was not in acceptable limits. The plus + operator combines character strings.
Continue by developing a test for minute values. Remember to give different names to each field!

2e: Character strings

A character string is defined by setting its value. Javascript assumes automatically that most variables are strings, unless a numerical value is clearly set. Character strings have properties such as length:
var mytext = "Some letters and also numbers 333";

var long = merkkijono.length;

Write a script where you define a string, and check its length with the previous commands. Write the result with some output command. Try also the following in your script:

mytext2 = mytext.toUpperCase();


There are several methods to manipulate character strings, for example to split them, extract only a part, or change case. Write a script where you try them, including the output commands to see the results:

mj = "cat"; mj2 ="fish"


concatenation: mj + mj2

Try to create "poetry" with a long string variable. The first character is 0. Use the random number generator to take parts of the string.

Programming hints

Programming always starts with planning: there is a problem that needs to be solved. Analyse the problem and needs, then outline the processing logic (using flowcharts) by separating input, processing, and output. If the problem is large, devide it into modules.

Software testing is an essential part of programming. Test all solutions in all possible cases, also with faulty input or error situations. Firefox, Chrome and IE have Javascript debuggers. You may test the logic also on paper by tracing variable values step by step. One way of checking intermediate values is to add extra output (such as alert boxes) to the code.


Created by: Jaana Holvikivi
Last update: 29.12.2012