Skip to content
Science, Maths & Technology
Author:

Getting Data From a User and Displaying Results

Updated Wednesday, 24th June 2015

Find out how to learn more about your user and use that data with JavaScript.

This page was published over five years ago. Please be aware that due to the passage of time, the information provided on this page may be out of date or otherwise inaccurate, and any views or opinions expressed may no longer be relevant. Some technical elements such as audio-visual and interactive media may no longer work. For more detail, see our Archive and Deletion Policy

Gathering Data

Keyboard Copyrighted  image Icon Copyright: Dreamstime So far, variables have been assigned values in the source code. But this is very inflexible. You can easily imagine that you might want to run a program with different values, e.g. a program which adds any two numbers. Providing a program with data which isn't written into the source code is known as getting input data for the program. There are various ways in which this can be done: the following activity shows one way.


Activity 1

Open getting_data_activity_1.html in your browser. You will see a box open on top of the browser's current page asking for your name. Boxes like this, with which a user interacts, are special kinds of windows called dialogue boxes.

Type in your name as instructed, and click OK. You shouldn't put quotes round your input, as JavaScript automatically interprets all input data as strings, as discussed below. You will then get a personalised greeting in the browser's current page.

Open the file in your text editor, and try to figure out how the source code works.

The JavaScript code is as follows (with line numbers included for reference).

(1) var name;
(2) name = window.prompt('Enter yourname','');
(3) document.write('Hello' + name + '!');
(4) document.write('<BR>'+ 'Have a good day');

The first line just declares a variable called name.

The second line instructs JavaScript to display a prompt dialogue box with some specified text. This box lets you enter a value, your name in this case, which is then assigned to the variable called name.

The third and fourth lines specify the program's output.

We shall now look at this code in more detail. In the second line, window refers to the browser's window in which document (the current page) is displayed. The method prompt() is associated with the window object, which will cause the prompt dialogue box to appear on top of the window.

The method prompt() can be used with two arguments, separated by a comma. The first of these specifies the string that the programmer wants to appear in the box ('Enter your name' in this case); the second specifies a default response string, which appears in the text entry box before the user has entered any value.

If the user fails to enter any text but clicks on the OK button without entering any text, this default value is the value assigned to the variable. In this case, the default string is the empty string '', consisting of no characters. Note that an empty string is written as two single quotes with nothing in between (''). It is not the same as ' ', which is two single quotes with a single space between them (i.e. a string consisting of a single space character) or ", which is double quotes.

Although we need to include the quotes when specifying strings in program code, they are not necessary when entering text into a prompt box; nor are strings displayed with quotes by the browser. JavaScript treats all input and output in these cases as strings, so does not need the quotes to distinguish them from other data types.

Question: How would you change the second line of the program code, so that the default string became 'Type your name here'?

Answer

The line of code would become:

name = window.prompt('Enter your name','Type your name here');

We now return to lines (3) and (4) of the code, which are repeated below.

(3) document.write('Hello ' + name + '!');
(4) document.write('<BR>' + 'Have a good day');

In line (3) we use the string concatenation operator + to make the three strings ('Hello', the value of the variable name and '!') into a single string.
In line (4), we use the HTML tag <BR>, which creates a line break, i.e. it causes the text which comes after it to be displayed on a new line in the browser's current page. <BR> may be thought of as a string consisting of a single character, the new line character. We concatenate this with the string 'Have a good day' to form a single string as the argument to write().

Now let's try modifying the code further.

(a) Open the file in the text editor and amend the source code so that the default input string is 'Type your name here', as in the question above. Save your changes. Run your amended program by opening it in your browser, but just click OK in the prompt dialogue box without modifying the default text. What happens?

(b) Amend the source code of your program so that the program also displays a second dialogue box asking you for the day today and displays output similar to the following:

Hello Charles Dickens!
Have a nice Thursday!

(substituting, of course, the name and day that you have entered instead of Charles Dickens and Thursday). Save the amended code and run the program.

Hint: How many variables will you need?

Solution

(a) The output is:

Hello Type your name here!
Have a good day

In the absence of the user inputting any value, the default string value, 'Type your name here', is assigned to the variable name.

(b) Here is our solution.

var name;
var day;
name = window.prompt('Enter your name','Type your name here');
day = window.prompt('Enter the day','');
document.write('Hello ' + name + '!');
document.write('<BR>' + 'Have a nice ' + day);

Note that you could have entered any old rubbish in response to the prompts. JavaScript doesn't automatically know what your name is, nor what day it is today, nor what is a sensible value for a name or a day. Note also that you don't need quotation marks around name and day in the document.write() statements, as it is the values of these variables that we want to display and not their identifiers.
If you're still having trouble with part (b), you can download our solution.

You wouldn't always want to include a non-empty default input string, as it is very irritating for the user to have to delete it before typing their input, but it can be useful in situations such as the following.

  • Where the programmer has good reason to expect a particular response from the user, e.g. if you were writing a program to ask if people studying on OpenLearn dislike learning, you would expect the most likely answer to be no, so you might use this as the default.
  • Where an empty string as the response could cause problems later on in the program, e.g. if you were asking a user to provide a name for a new file.

(c) Now try writing a line of JavaScript code which will cause a dialogue box to appear with the prompt: Please enter yes, no or quit, and which provides a default answer of 'quit', and will assign whatever is entered into the dialogue box should be assigned to a variable with the identifier answer.

(d) Write a second line of code which will display the following message on the screen:
You have entered (followed by whatever was entered: yes, no or quit)

Solution

You should have written something like the following:

(c) answer = window.prompt('Please enter yes, no or quit','quit');
(d) document.write('You have entered ' + answer);​


Getting Numbers as Input

In JavaScript all input from the keyboard is assumed to be strings. So far this has not been an issue, as all our programs have involved the manipulation of text. But, as you're about to find out, things are not so straightforward if you want to enter numbers.


Activity 2

The following code is from getting_data_activity_2.html (with line numbers added for reference).

(1) var numberOne;
(2) var numberTwo;
(3) var sum;
(4) numberOne = window.prompt('Enter your first number','');
(5) numberTwo = window.prompt('Enter your second number','');
(6) sum = numberOne + numberTwo;
(7) document.write('The sum of '+ numberOne + ' and ' + numberTwo + ' is ' + sum);

Study the code and without running it, try to work out what the output will be when you enter the two numbers 32 and 45 in response to the prompts. Run the program using your browser and see whether you are right.

Solution

You might have expected to get the output:

The sum of 32 and 45 is 77

In fact, what you got was:

The sum of of 32 and 45 is 3245

JavaScript will assume that both your inputs were strings, i.e. '32' and '45', and will therefore have understood + to be the concatenation operator.

So if we want to read in and add two numbers, how do we do it? We use a function called parseFloat(). A function is similar to a method but isn't attached to any particular object. The funtion parseFloat() takes a string as argument and provides as a result the number corresponding to the numeric part of the string. In programming, the result provided by the function is known as its return value. We say that the function returns some value.

You may think of parseFloat() as converting a suitable string into a number. For example,

parseFloat('3') returns 3

parseFloat('10.25') returns 10.25

If we have two lines of code as follows:

(1) myVar = window.prompt('Enter a number','');
(2) myVar = parseFloat(myVar);

the digits entered will first be assigned as a string to myVar (in line 1) and then converted to a number and reassigned to myVar (in line 2).

Question: Suppose that the two lines of code above are executed and that, in response to the prompt, the user enters 77.

(a) What is the value of myVar after execution of line (1)?

(b) What is the value of myVar after execution of line (2)?

Answer

(a) '77'; the input is initially read in as a string.
(b) 77; in line (2) the function parseFloat() converts the string into a number.


Outputting numbers

 We said above that the argument to document.write() must be a string (which may be formed from the concatenation of several strings). So what happens when you want to output a number? There is no problem here: the method write() takes a number, 183 say, and automatically converts it to the string of numeric characters, '183'.


Activity 3

(a) Run getting_data_activity_3.html in your browser and supply various different number inputs. How does the output of this program differ from the output of the one you looked at in activity 2?

(b) What happens when you input a number in letters rather than numerals, e.g. if you enter thirty-two rather than 32?

(c) Study the code for getting_data_activity_3.html, in particular the use of parseFloat().

Solution

(a)The program correctly adds the two numbers, rather than concatenating two strings as you've seen already.

(b) You will get output similar to the following:
The sum of NaN and NaN is NaN
Although JavaScript will correctly read in your two inputs, say thirtytwo and twelve, parseFloat() will not be able to convert them into numbers as there is no way that JavaScript can know that these strings represent the numbers 32 and 12. As you might guess, NaN is JavaScript's shorthand for 'Not a Number'

(c) The code for the program is as follows (with line numbers added for reference).

(1) var firstNumber;
(2) var secondNumber;
(3) var total;
(4) firstNumber = window.prompt('Enter your first number','');
(5) firstNumber = parseFloat(firstNumber);
(6) secondNumber = window.prompt('Enter your second number','');
(7) secondNumber = parseFloat(secondNumber);
(8) total = firstNumber + secondNumber;
(9) document.write('The sum of '+ firstNumber + ' and ' + secondNumber + ' is ' + total);

The use of parseFloat() in lines (5) and (7) takes the string argument and returns the corresponding number. For example, if you enter the value 3 at the prompt in line (4), and 7 at the prompt in line (6), both will be converted to numbers and added together in line (8), so that total will be assigned a value of 10. The output string displayed by line (9) will consist of the concatenation of the given character strings, together with the value of total converted to a numeric string.


Activity 4

The file javascript_template.html contains an HTML template to which you can add JavaScript code.

(a) Add JavaScript code to the file (between the <SCRIPT> and </SCRIPT> tags) to do the following: prompt the user to input first their telephone area code (e.g. 01908) and then their local telephone number (e.g. 6123456), after which the program should display output similar to the following

Your telephone number is 01908 6123456

(or whatever numbers you have input).

(b) Why don't you need to use parseFloat() in this situation?

(c) What happens if you do, and why?

Solution

(a) Here is our solution:

var areaCode;
var localNumber;

areaCode = window.prompt('Please enter your area code','');
localNumber = window.prompt('Please enter your local telephone number','');
document.write('Your telephone number is ' + areaCode + ' ' + localNumber);

The output string in your solution may differ. Did you remember to include spaces to separate your words?

(b) You don't need parseFloat() because you are considering the telephone numbers to be strings of numeric characters rather than numbers.

(c) If you insert the lines

areaCode = parseFloat(areaCode);

and

localNumber = parseFloat(localNumber);

after the prompts, then the values assigned to areaCode and localNumber will be numbers. As 01908 is the same number as 1908, the leading zero will be lost, and the number will be converted to the string '1908' for use by document.write(), leading to an output of:
Your telephone number is 1908 6123456

You can download our solution if required.

In Getting Started if you have completed all the articles you have already started writing your own programs in JavaScript. You began by displaying output in the browser's current page. You were then introduced to the concept of a variable and to the way in which variables are assigned values. You learned about two data types, numbers and strings, and about some simple operations which can be performed on them. You also saw how you can obtain input from a user via a dialogue box. Since values input in this way are, by default, strings, we showed how you can use the function parseFloat() to convert numeric strings to numbers.

If you want to learn more about some standard JavaScript styles and good practices, take a look at our JavaScript Style and Layout article. Otherwise, move onto the next part of our series on learning to program using JavaScript by starting on 'if' statements below.

 

Ratings

Share

Related content (tags)

Copyright information

For further information, take a look at our frequently asked questions which may give you the support you need.

Have a question?